using C1.Xaml.Pdf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Graphics.Imaging;
using Windows.UI.Core;

namespace PdfSamples
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class ImagesPage : Page
    {
        C1PdfDocument pdf;

        public ImagesPage()
        {
            this.InitializeComponent();
            this.Loaded += ImagesPage_Loaded;

            pdf = new C1PdfDocument(PaperKind.Letter);
            pdf.Clear();
        }

        async void ImagesPage_Loaded(object sender, RoutedEventArgs e)
        {
            progressRing.IsActive = true;
            await CreateDocumentImages(pdf);
            PdfUtils.SetDocumentInfo(pdf, "Images");
            await c1PdfViewer1.LoadDocumentAsync(PdfUtils.SaveToStream(pdf));
            progressRing.IsActive = false;
        }
        
        async Task CreateDocumentImages(C1PdfDocument pdf)
        {
            // calculate page rect (discounting margins)
            Rect rcPage = PdfUtils.PageRectangle(pdf);
            InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream();
            // load image into writeable bitmap
            WriteableBitmap wb = new WriteableBitmap(880, 660);
            var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///PdfSamplesLib/Resources/pic.jpg"));
            
            wb.SetSource(await file.OpenReadAsync());
            Rect rcPic = new Rect(new Point(0, 0), new Point(pdf.PageSize.Width, pdf.PageSize.Height));

            // draw on page preserving aspect ratio
            pdf.DrawImage(wb, rcPic, ContentAlignment.MiddleCenter, Stretch.Uniform);
        }
    }
}
