using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml.Linq;

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

using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

using C1.Xaml.FlexReport;
using FlexReportExplorer.Data;

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

        private Manage Mng = new Manage();
        public MainPage()
        {
            this.InitializeComponent();

            this.Loaded += MainPage_Loaded;

            _report = new C1FlexReport();
        }

        async void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            //Create Left Panel Menus
            string XMLPath = Path.Combine("Assets", "ReportsDetail.xml");
            System.IO.Stream file = File.OpenRead(XMLPath);
            XDocument xdoc = new XDocument();
            xdoc = XDocument.Load(file);
            IEnumerable<XElement> xelems = xdoc.Descendants("Category");
            List<Category> ItemSource = new List<Category>();
            foreach (XElement xelem in xelems)
            {
                Category category = new Category();
                category.Name = xelem.Attribute("Name").Value;
                category.Text = xelem.Attribute("Text").Value;
                category.ImageUri = "Resources/Reports/MenuIcons/" + xelem.Attribute("Image").Value + ".png";
                List<Report> Reports = new List<Report>();
                foreach (XElement childReports in xelem.Descendants("Report"))
                {
                    Report report = new Report();
                    report.CategoryName = category.Name;
                    report.ReportName = childReports.Descendants("ReportName").First().Value;
                    report.FileName = childReports.Descendants("FileName").First().Value;
                    report.ReportTitle = childReports.Descendants("ReportTitle").First().Value;
                    report.ImageUri = "Resources/Reports/" + category.Name.Trim() + "/Images/" + childReports.Descendants("ImageName").First().Value.Trim();
                    Reports.Add(report);
                }
                category.Reports = Reports;
                ItemSource.Add(category);
            }
            ReflectionTreeView.ItemsSource = ItemSource;

            //Create db connection
            Assembly asm = typeof(MainPage).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("FlexReportExplorer.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();
                    }
                }
            }

            XElement xelemDef = xdoc.Descendants("SelectedReport").First();
            if(xelemDef!=null)
            {
                string DefCategoryName = xelemDef.Descendants("CategoryName").FirstOrDefault().Value;
                string DefRepName = xelemDef.Descendants("ReportName").FirstOrDefault().Value;
                string DefRepfileName = xelemDef.Descendants("FileName").FirstOrDefault().Value;
                LoadReport(DefCategoryName, DefRepfileName, DefRepName);
            }

        }

        private void ReflectionTreeView_ItemClick(object sender, C1.Xaml.SourcedEventArgs e)
        {
            try
            {
                C1.Xaml.C1TreeViewItem SelItem = ReflectionTreeView.SelectedItem;
                if (SelItem.DataContext.ToString() == "FlexReportExplorer.Report")
                {
                    Report ReportTemplate = (Report)SelItem.DataContext;
                    string selectedReport = ReportTemplate.ReportName;
                    if (string.IsNullOrEmpty(selectedReport))
                        return;

                    // load report
                    LoadReport(ReportTemplate.CategoryName.Trim(), ReportTemplate.FileName, ReportTemplate.ReportName);
                    //try
                    //{
                    //    Assembly asm = typeof(MainPage).GetTypeInfo().Assembly;
                    //    string fileName = "FlexReportExplorer.Resources.Reports." + ReportTemplate.CategoryName.Trim() + "." + ReportTemplate.FileName.Trim();
                    //    //string fileName = "FlexReportExplorer.Resources." + ReportTemplate.FileName.Trim();
                    //    using (Stream stream = asm.GetManifestResourceStream(fileName))
                    //        _report.Load(stream, selectedReport);
                    //}
                    //catch (Exception ex)
                    //{
                    //    MessageDialog md = new MessageDialog(string.Format("Error in {0}: {1}", selectedReport, ex.Message), "Error");
                    //    await md.ShowAsync();
                    //    return;
                    //}

                    //// 
                    //flexViewerPane.DocumentSource = null;

                    //// render report
                    //prViewer.IsActive = true;
                    //try
                    //{
                    //    await _report.RenderAsync();
                    //}
                    //catch (Exception ex)
                    //{
                    //    MessageDialog md = new MessageDialog(string.Format("Error in {0}: {1}", selectedReport, ex.Message), "Error");
                    //    await md.ShowAsync();
                    //    return;
                    //}
                    //finally
                    //{
                    //    prViewer.IsActive = false;
                    //}

                    //// assign rendered report to the viewer
                    //flexViewerPane.DocumentSource = _report;
                }
            }
            catch (Exception ex)
            {
            }
        }

        async private void LoadReport(string CategoryName,string ReportFileName,string ReportName)
        {
            // load report
            try
            {
                Assembly asm = typeof(MainPage).GetTypeInfo().Assembly;
                ReportFileName = "FlexReportExplorer.Resources.Reports." + CategoryName.Trim() + "." + ReportFileName.Trim();
                using (Stream stream = asm.GetManifestResourceStream(ReportFileName))
                    _report.Load(stream, ReportName);
            }
            catch (Exception ex)
            {
                MessageDialog md = new MessageDialog(string.Format("Error in {0}: {1}", ReportName, ex.Message), "Error");
                await md.ShowAsync();
                return;
            }

            // 
            flexViewerPane.DocumentSource = null;

            // render report
            prViewer.IsActive = true;
            try
            {
                await _report.RenderAsync();
            }
            catch (Exception ex)
            {
                MessageDialog md = new MessageDialog(string.Format("Error in {0}: {1}", ReportName, ex.Message), "Error");
                await md.ShowAsync();
                return;
            }
            finally
            {
                prViewer.IsActive = false;
            }

            // assign rendered report to the viewer
            flexViewerPane.DocumentSource = _report;
        }

    }
}
