using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows.Controls;
using System.Xml.Linq;
using System;
using C1.Silverlight.Chart;
using System.Windows.Media;
using System.Globalization;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Resources;
using System.Windows.Media.Imaging;
using C1.Silverlight.Extended;
using System.Windows.Input;
using System.Diagnostics;

namespace SalesBook
{
    public partial class Page : UserControl
    {
        public class Employee
        {
            public string Name { get; set; }
            public string Phone { get; set; }
            public string JobTitle { get; set; }
            public string BirthDate { get; set; }
            public string Email { get; set; }
            public string City { get; set; }
            public string AddressLine { get; set; }
            public string HireDate { get; set; }
            public string Photo { get; set; }
        }

        public class Sales
        {
            public string Name { get; set; }
            public double y2005 { get; set; }
            public double y2006 { get; set; }
            public double y2007 { get; set; }
        }

        public Page()
        {
            InitializeComponent();

            LoadSales();
            LoadEmployees();
            legend.Chart = salesChart;

            BookContainer.SizeChanged += new SizeChangedEventHandler(BookContainer_SizeChanged);
        }

        void BookContainer_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            //830x496
            double width, height;
            if (e.NewSize.Width / 830 < e.NewSize.Height / 496)
            {
                width = e.NewSize.Width;
                height = e.NewSize.Width * 496 / 830;
            }
            else
            {
                width = e.NewSize.Height * 830 / 496;
                height = e.NewSize.Height;
            }
            book.Width = width;
            book.Height = height;
        }

        private void LoadSales()
        {
            //Loads sales xml from a embedded resource
            XDocument doc = XDocument.Load(new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("SalesBook.resources.sales.xml")));
            var sales = from sale in doc.Descendants("Sale")
                        select new Sales
                        {
                            Name = sale.Element("Name").Value,
                            y2005 = (sale.Element("y2005").Value.Length > 0 ? double.Parse(sale.Element("y2005").Value, CultureInfo.InvariantCulture.NumberFormat) : 0),
                            y2006 = (sale.Element("y2006").Value.Length > 0 ? double.Parse(sale.Element("y2006").Value, CultureInfo.InvariantCulture.NumberFormat) : 0),
                            y2007 = (sale.Element("y2007").Value.Length > 0 ? double.Parse(sale.Element("y2007").Value, CultureInfo.InvariantCulture.NumberFormat) : 0),
                        };

            //Loads data into the charts
            salesChart.Data.Children.Clear();
            salesPieChart.Data.Children.Clear();
            salesPieChart.Data.Children.Add(new DataSeries() { Values = new DoubleCollection() });
            List<string> sellerNames = new List<string>();
            foreach (var sale in sales)
            {
                DataSeries serie = new DataSeries() { Values = new DoubleCollection() };
                serie.Label = sale.Name;
                serie.Values.Add(sale.y2005);
                serie.Values.Add(sale.y2006);
                serie.Values.Add(sale.y2007);
                salesChart.Data.Children.Add(serie);
                salesPieChart.Data.Children[0].Values.Add(sale.y2007);
                sellerNames.Add(sale.Name);
            }
            salesPieChart.Data.ItemNames = sellerNames;
            salesChart.Data.ItemNames = new string[] { "2005", "2006", "2007" };
        }

        private void LoadEmployees()
        {
            XDocument doc = XDocument.Load(new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("SalesBook.resources.employees.xml")));
            var employess = from employee in doc.Descendants("Employee")
                            select new Employee
                            {
                                Name = employee.Element("Name").Value,
                                Phone = employee.Element("Phone").Value,
                                JobTitle = employee.Element("JobTitle").Value,
                                BirthDate = employee.Element("BirthDate").Value,
                                Email = employee.Element("Email").Value,
                                City = employee.Element("City").Value,
                                AddressLine = employee.Element("AddressLine").Value,
                                HireDate = employee.Element("HireDate").Value,
                                Photo = new AssemblyName(Assembly.GetExecutingAssembly().FullName).Name + ";component" + employee.Element("Photo").Value
                            };
            foreach (var employee in employess)
            {
                book.Items.Insert(book.Items.Count - 1, employee);
            }
        }

        #region ** tooltip

        ToolTip _tooltip = new ToolTip();
        bool _dragging = false;

        private void book_CurrentZoneChanged(object sender, C1.Silverlight.PropertyChangedEventArgs<C1.Silverlight.Extended.BookZone> e)
        {
            Debug.WriteLine("CurrentZone {0}", e.NewValue);
        }

        private void book_DragPageStarted(object sender, EventArgs e)
        {
            _dragging = true;
            Debug.WriteLine("DragPageStarted {0} {1}", book.CurrentPage, DateTime.Now);
        }

        private void book_DragPageFinished(object sender, EventArgs e)
        {
            _dragging = false;
            Debug.WriteLine("DragPageFinished {0} {1}", book.CurrentPage, DateTime.Now);
        }

        private void book_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            HideTooltip();
            if ((book.CurrentZone == BookZone.BottomLeft ||
                book.CurrentZone == BookZone.TopLeft ||
                book.CurrentZone == BookZone.BottomRight ||
                book.CurrentZone == BookZone.TopRight) && !_dragging)
            {
            }
        }

        private void ShowTooltip()
        {
            book.Cursor = Cursors.Hand;
            _tooltip.Content = new TextBlock() { Text = "Click here to turn the page" };
            _tooltip.IsOpen = true;
        }

        private void HideTooltip()
        {
            book.Cursor = Cursors.Arrow;
            _tooltip.IsOpen = false;
        }

        #endregion

    }

    public class ImageSourceConverter : System.Windows.Data.IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string s = value as string;

            if (!string.IsNullOrEmpty(s))
            {
                // get image from resources
                StreamResourceInfo sri = Application.GetResourceStream(new Uri(s, UriKind.Relative));
                if (sri != null && sri.Stream != null)
                {
                    BitmapImage bi = new BitmapImage();
                    bi.SetSource(sri.Stream);
                    return bi;
                }
            }

            return s;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
