using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using C1.Silverlight;
using System.Reflection;

namespace Reports
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();

            reports.ItemsSource = new[]
            {
                "Alphabetical List of Products",
                "Casual Products Report",
                "Company Sales",
                "Employee Sales",
                "Sales by Category",
                "Sales Order Detail",
                "Suppliers",
                "Territory Sales Drilldown",
            };
            reports.SelectedIndex = 3;
            reportViewer.LoadDocument(Application.GetResourceStream(new Uri("/" + new AssemblyName(Assembly.GetExecutingAssembly().FullName).Name + ";component/Employee Sales.pdf", UriKind.Relative)).Stream);
            reports.SelectedItemChanged += OnSelectedItemChanged;
        }

        void OnSelectedItemChanged(object sender, PropertyChangedEventArgs<object> args)
        {
            var report = (string)reports.SelectedItem;
            var client = new WebClient();
            client.OpenReadAsync(Extensions.GetAbsoluteUri("reports/" + report + (pdfFormat.IsChecked == true ? ".pdf" : ".mhtml")));
            loadingReport.Visibility = Visibility.Visible;
            client.OpenReadCompleted += (s, e) =>
            {
                if (e.Error == null)
                {
                    reportViewer.LoadDocument(e.Result);
                }
                else
                {
                    C1MessageBox.Show("Couldn't get report from server.", "Error", C1MessageBoxIcon.Error);
                }
                loadingReport.Visibility = Visibility.Collapsed;
            };
        }

        private void FormatClick(object sender, RoutedEventArgs e)
        {
            OnSelectedItemChanged(null, null);
        }
    }
}
