using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI;
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.Navigation;

// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236

namespace PdfViewerSamples
{
    public sealed partial class Thumbnails : UserControl
    {
        public Thumbnails()
        {
            this.InitializeComponent();
            this.Loaded += Thumbnails_Loaded;
            this.Unloaded += Thumbnails_Unloaded;
        }

        void Thumbnails_Unloaded(object sender, RoutedEventArgs e)
        {
            pdfviewer.CloseDocument();
            stackThumbnail.Children.Clear();
        }

        void Thumbnails_Loaded(object sender, RoutedEventArgs e)
        {
            Assembly asm = typeof(PdfViewerDemoPage).GetTypeInfo().Assembly;
            Stream stream = asm.GetManifestResourceStream("PdfViewerSamples.Files.PdfViewer.pdf");
            //pdfviewer.RenderMode = C1.Xaml.PdfViewer.RenderMode.System;
            pdfviewer.LoadDocument(stream);
            
            RefreshThumbnail();
        }

        private void RefreshThumbnail()
        {
            C1.Xaml.PdfViewer.C1PdfViewer viewer = new C1.Xaml.PdfViewer.C1PdfViewer();
            Assembly asm = typeof(PdfViewerDemoPage).GetTypeInfo().Assembly;
            Stream stream = asm.GetManifestResourceStream("PdfViewerSamples.Files.PdfViewer.pdf");
            viewer.RenderMode = C1.Xaml.PdfViewer.RenderMode.System;
            viewer.LoadDocument(stream);
            IList<FrameworkElement> pages = viewer.GetPages();
            for (int i = 0; i < pages.Count; i++)
            {
                FrameworkElement fe = pages[i];
                Border b = new Border() { BorderThickness = new Thickness(3), BorderBrush= new SolidColorBrush(Colors.LightGray) };
                b.Child = fe;
                Canvas content = new Canvas() { Background = new SolidColorBrush(Colors.White) };
                content.Width = fe.Width;
                content.Height = fe.Height;
                
                content.Children.Add(b);
                
                Viewbox viewbox = new Viewbox() { Margin = new Thickness(10), Child = content, Tag = i };
                viewbox.PointerReleased += viewbox_PointerReleased;
                this.stackThumbnail.Children.Add(viewbox);
            }
        }

        void viewbox_PointerReleased(object sender, PointerRoutedEventArgs e)
        {
            int pageIndex = int.Parse(((FrameworkElement)sender).Tag.ToString());
            this.pdfviewer.GoToPage(pageIndex + 1);
        }
    }
}
