using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Reflection;
using System.Runtime.InteropServices.WindowsRuntime;

using Windows.Foundation;
using Windows.Foundation.Collections;

using Windows.Storage;
using Windows.UI.Popups;

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;

using C1.Xaml.FlexReport;

namespace FlexReportSamples
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class ViewerPage : Page
    {
        C1FlexReport _report;

        public ViewerPage()
        {
            this.InitializeComponent();
            this.Unloaded += ViewerPage_Unloaded;
            this.Loaded += ViewerPage_Loaded;

            _report = new C1FlexReport();
        }

        void ViewerPage_Unloaded(object sender, RoutedEventArgs e)
        {
            cbReport.SelectionChanged -= CbReport_SelectionChanged;
        }

        async void ViewerPage_Loaded(object sender, RoutedEventArgs e)
        {
            Assembly asm = typeof(ExportPage).GetTypeInfo().Assembly;
            var f = await ApplicationData.Current.LocalFolder.TryGetItemAsync("C1NWind.db");
            if (f == null)
            {
                // copy SQLite database from resources to the local folder
                using (Stream stream = asm.GetManifestResourceStream("FlexReportSamples.Resources.C1NWind.db"))
                {
                    StorageFile sf = await ApplicationData.Current.LocalFolder.CreateFileAsync("C1NWind.db", CreationCollisionOption.ReplaceExisting);
                    using (Stream dst = await sf.OpenStreamForWriteAsync())
                    {
                        await stream.CopyToAsync(dst);
                        await dst.FlushAsync();
                    }
                }
            }

            string[] reports = null;

            // get list of reports from resource using stream
            using (Stream stream = asm.GetManifestResourceStream("FlexReportSamples.Resources.FlexCommonTasks_UWP.flxr"))
                reports = C1FlexReport.GetReportList(stream);

            cbReport.Items.Clear();
            cbReport.SelectionChanged += CbReport_SelectionChanged;

            if (reports != null && reports.Length > 0)
            {
                foreach (string s in reports)
                    cbReport.Items.Add(s);
                cbReport.SelectedIndex = 0;
            }
        }

        async void CbReport_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string selectedReport = cbReport.SelectedItem as string;
            if (string.IsNullOrEmpty(selectedReport))
                return;

            // load report
            try
            {
                // load from resource stream
                Assembly asm = typeof(ExportPage).GetTypeInfo().Assembly;
                using (Stream stream = asm.GetManifestResourceStream("FlexReportSamples.Resources.FlexCommonTasks_UWP.flxr"))
                    _report.Load(stream, selectedReport);
            }
            catch (Exception ex)
            {
                MessageDialog md = new MessageDialog(string.Format(Strings.FailedToLoadFmt, selectedReport, ex.Message), "Error");
                await md.ShowAsync();
                return;
            }

            flexViewerPane.DocumentSource = null;
            flexViewerPane.DocumentSource = _report;
        }
    }
}