using System;
using System.IO;
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.Imaging;
using System.Windows.Printing;
using System.Windows.Shapes;
using System.Diagnostics;

using C1.Silverlight.Excel;

namespace PrintSettings
{
    public partial class MainPage : UserControl
    {
        Dictionary<short, string> _papers;
        C1XLBook _book;

        public MainPage()
        {
            InitializeComponent();

            _papers = new Dictionary<short, string>();
            _papers.Add(1, "Letter");
            _papers.Add(2, "Letter small");
            _papers.Add(3, "Tabloid");
            _papers.Add(4, "Ledger");
            _papers.Add(5, "Legal");
            _papers.Add(6, "Statement");
            _papers.Add(7, "Executive");
            _papers.Add(8, "A3");
            _papers.Add(9, "A4");
            _papers.Add(10, "A4 small");
            _papers.Add(11, "A5");
            _papers.Add(12, "B4");
            _papers.Add(13, "B5");
            _papers.Add(14, "Folio");
            _papers.Add(15, "Quarto");
            _papers.Add(18, "Note");
            _papers.Add(66, "A2");
            _papers.Add(70, "A6");

            _book = new C1XLBook();
        }

        private void _btnLoad_Click(object sender, RoutedEventArgs e)
        {
            Debug.Assert(_book != null);
            var dlg = new OpenFileDialog();
            dlg.Filter = "Excel Files (*.xlsx)|*.xlsx";
            if (dlg.ShowDialog().Value)
            {
                try
                {
                    _lblStatus.Text = string.Format("Loading {0}...", dlg.File.Name);

                    using (Stream stream = dlg.File.OpenRead())
                    {
                        _book.Load(stream, FileFormat.OpenXml);
                    }

                    ShowPrintSettings();
                    
                    _lblStatus.Text = "Ready";
                    _btnSave.IsEnabled = true;
                }
                catch (Exception x)
                {
                    MessageBox.Show(x.Message);
                }
            }
        }

        private void _btnSave_Click(object sender, RoutedEventArgs e)
        {
            Debug.Assert(_book != null);
            var dlg = new SaveFileDialog();
            dlg.Filter = "Excel Files (*.xlsx)|*.xlsx";
            if (dlg.ShowDialog().Value)
            {
                try
                {
                    // information
                    _lblStatus.Text = string.Format("Saving {0}...", dlg.SafeFileName);

                    // apply
                    ApplyPrintSettings();

                    // save workbook
                    using (var stream = dlg.OpenFile())
                    {
                        _book.Save(stream);
                    }
                    _lblStatus.Text = string.Format("Saved {0}", dlg.SafeFileName); ;
                }
                catch (Exception x)
                {
                    MessageBox.Show(x.Message);
                }
            }
        }

        private int GetPaperSelected(string name)
        {
            int index = -1;
            _cmbPaperSize.Items.Clear();
            foreach (var value in _papers.Values)
            {
                if (value.ToUpper().Equals(name.ToUpper()))
                    index = _cmbPaperSize.Items.Count;
                _cmbPaperSize.Items.Add(value);
            }
            return index;  // A4
        }
        private short GetPaperCode(string name)
        {
            foreach (var key in _papers.Keys)
            {
                var value = _papers[key];
                if (value.ToUpper().Equals(name.ToUpper()))
                    return key;
            }
            return 9;   // A4
        }
        private string GetPaperName(int code)
        {
            foreach (var key in _papers.Keys)
            {
                if (key == code)
                    return _papers[key];
            }
            return "A4";
        }

        private void LayoutRoot_Loaded(object sender, RoutedEventArgs e)
        {
            _cmbPaperSize.SelectedIndex = GetPaperSelected("A4");
        }

        // read print settings from sheet, show in form
        private void ShowPrintSettings()
        {
            XLSheet sheet = _book.Sheets[0];
            XLPrintSettings ps = sheet.PrintSettings;

            // paper size, orientation
            _cmbPaperSize.SelectedIndex = GetPaperSelected(GetPaperName(ps.PaperKind));
            if (ps.Landscape)
            {
                _rdLandscape.IsChecked = true;
            }
            else
            {
                _rdPortrait.IsChecked = true;
            }

            // scaling
            if (ps.AutoScale)
            {
                _rdFit.IsChecked = true;
            }
            else
            {
                _rdAdjust.IsChecked = true;
            }
            _udAcross.Value = ps.FitPagesAcross;
            _udDown.Value = ps.FitPagesDown;
            _udPercentSize.Value = ps.ScalingFactor;

            // start page
            _txtStartPage.Text = ps.StartPage.ToString();

            // margins
            _udLeftMrgs.Value = ps.MarginLeft;
            _udTopMrgs.Value = ps.MarginTop;
            _udRightMrgs.Value = ps.MarginRight;
            _udBottomMrgs.Value = ps.MarginBottom;
            _udHeader.Value = ps.MarginHeader;
            _udFooter.Value = ps.MarginFooter;

            // header/footer
            _txtHeader.Text = ps.Header;
            _txtFooter.Text = ps.Footer;
        }

        // read print settings from form, apply to sheet
        private void ApplyPrintSettings()
        {
            XLSheet sheet = _book.Sheets[0];
            XLPrintSettings ps = sheet.PrintSettings;

            // paper size, orientation
            if (_cmbPaperSize.SelectedItem != null)
            {
                ps.PaperKind = GetPaperCode(_cmbPaperSize.SelectedItem.ToString());
            }
            ps.Landscape = _rdLandscape.IsChecked.HasValue ? _rdLandscape.IsChecked.Value : false;

            // scaling
            // ** note: 
            //    setting the FitPagesAcross, FitPagesDown, and ScalingFactor properties
            //    changes the value of AutoScale, so set AutoScale last.
            ps.FitPagesAcross = (int)Math.Round(_udAcross.Value);
            ps.FitPagesDown = (int)Math.Round(_udDown.Value);
            ps.ScalingFactor = (int)Math.Round(_udPercentSize.Value);
            ps.AutoScale = _rdFit.IsChecked.HasValue ? _rdFit.IsChecked.Value : false;

            // start page
            try
            {
                ps.StartPage = int.Parse(_txtStartPage.Text);
            }
            catch
            {
                ps.StartPage = 1;
            }

            // margins
            ps.MarginLeft = _udLeftMrgs.Value;
            ps.MarginTop = _udTopMrgs.Value;
            ps.MarginRight = _udRightMrgs.Value;
            ps.MarginBottom = _udBottomMrgs.Value;
            ps.MarginHeader = _udHeader.Value;
            ps.MarginFooter = _udFooter.Value;

            // header/footer
            ps.Header = _txtHeader.Text;
            ps.Footer = _txtFooter.Text;
        }
    }
}
