namespace SalesAnalysis
{
    using System.Collections;
    using System.ComponentModel;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Navigation;
    using C1.Silverlight.FlexGrid;

    /// <summary>
    /// <see cref="Page"/> class to present a grid populated with the Invoices information.
    /// </summary>
    public partial class Invoices : Page
    {
        /// <summary>
        /// Creates a new instance of the <see cref="Invoices"/> class.
        /// </summary>
        public Invoices()
        {
            InitializeComponent();

            this.Title = ApplicationStrings.InvoicesPageTitle;
        }

        /// <summary>
        /// Executes when the user navigates to this page.
        /// </summary>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // loading data without a DomainDataSource control
            //var ctx = new SalesAnalysis.Web.NorthWindDomainContext();
            //_flex.ItemsSource = ctx.Invoices;
            //ctx.Load(ctx.GetInvoicesQuery());
        }

        //----------------------------------------------------------------------------
        #region ** monitor data download status

        void _ddsInvoices_LoadingData(object sender, LoadingDataEventArgs e)
        {
            _tbStatus.Text = "Loading invoices...";
        }
        void _ddsInvoices_LoadedData(object sender, LoadedDataEventArgs e)
        {
            // note: entity counts in 'e' parameter are bogus
            // looking directly in the ICollectionView works OK.
            var view = _flex.ItemsSource as ICollectionView;
            var list = view.SourceCollection as IList;
            _tbStatus.Text = string.Format("{0:n0} invoices loaded", list.Count);
        }

        #endregion

        //----------------------------------------------------------------------------
        #region ** handle filter

        void _txtFilter_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == System.Windows.Input.Key.Enter)
                ApplyFilter();
        }
        void _txtFilter_LostFocus(object sender, System.Windows.RoutedEventArgs e)
        {
            ApplyFilter();
        }
        void _imgFilter_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            ApplyFilter();
        }
        void ApplyFilter()
        {
            // remove old filter
            var fop = _ddsInvoices.FilterDescriptors;
            fop.Clear();

            // apply new filter (if any)
            var txt = _txtFilter.Text;
            if (!string.IsNullOrEmpty(txt))
            {
                fop.Add(new FilterDescriptor("ProductName", FilterOperator.Contains, txt));
            }
        }

        #endregion

        //----------------------------------------------------------------------------
        #region ** save invoices

        void _btnSave_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            // show dialog
            var dlg = new SaveFileDialog();
            dlg.DefaultExt = "csv";
            dlg.Filter =
                "Comma Separated Values (*.csv)|*.csv|" +
                "Plain text (*.txt)|*.txt|" +
                "HTML (*.html)|*.html";
            if (dlg.ShowDialog().Value)
            {
                // select format based on file extension
                var fileFormat = FileFormat.Csv;
                switch (System.IO.Path.GetExtension(dlg.SafeFileName).ToLower())
                {
                    case ".htm":
                    case ".html":
                        fileFormat = FileFormat.Html;
                        break;
                    case ".txt":
                        fileFormat = FileFormat.Text;
                        break;
                }

                // save the file
                using (var stream = dlg.OpenFile())
                {
                    _flex.Save(stream, fileFormat);
                }
            }
        }

        #endregion

        //----------------------------------------------------------------------------
        #region ** print invoices

        // print the grid: scale to fit page width, use a 1 inch margin, and limit output to 20 pages
        void _btnPrint_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            _flex.Print("NorthWind Invoices", ScaleMode.PageWidth, new Thickness(96), 20);
        }

        #endregion
    }
}