using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using C1.Silverlight.Legacy;
using C1.Silverlight.Chart;
using StockPortfolio.localhost;

namespace StockPortfolio
{
    public partial class Page : UserControl
    {
        ChartSlider     _slider;
        C1ScrollBar     _sb;
        SearchBox       _txtbox;
        ButtonAdd       _btnAdd;

        C1StackPanel    _symHolder;
        C1StackPanel    _zoomButtons;
        C1Chart         _chartUpper;
        C1Chart         _chartLower;

        C1Label         _lblDateRange;

        ChartLogic      _logic;

        ActiveStockButton _selectedSym;     // the button that represents the symbol selected in the grid

        CompanyInfo _companyInfo;

        public void InitializeChart()
        {
            // anno template for both charts
            TextBlock anno = new TextBlock();
            anno.FontFamily = new FontFamily("Lucida Sans Unicode");
            anno.FontSize = 9;

            // upper chart
            _chartUpper = new C1Chart();
            _chartUpper.Palette = Palette.Standard;
            _chartUpper.ChartType = ChartType.Area;
            _chartUpper.View.Margin = new Thickness(50, 10, 20, 15);
            _chartUpper.View.AxisX.MajorGridStroke = new SolidColorBrush(Color.FromArgb(0xFF, 0xD9, 0xD9, 0xD9));
            _chartUpper.View.AxisY.MajorGridStroke = new SolidColorBrush(Color.FromArgb(0xFF, 0xD9, 0xD9, 0xD9));
            _chartUpper.View.AxisX.MinorTickHeight = 0;
            _chartUpper.View.AxisX.AnnoTemplate = anno;
            _chartUpper.View.AxisY.AnnoTemplate = anno;
            _chartUpper.View.AxisX.IsTime = true;
            _chartUpper.View.AxisX.AnnoFormat = "MMM dd, yyyy";
            _chartUpper.View.AxisX.AnnoPosition = AnnoPosition.Near;
            _chartUpper.LegendChanged += new EventHandler(_chartUpper_LegendChanged);

            // lower chart
            _chartLower = new C1Chart();
            _chartLower.View.Margin = new Thickness(50, 5, 20, 15);
            _chartLower.View.AxisX.MajorGridStroke = new SolidColorBrush(Color.FromArgb(0xFF, 0xD9, 0xD9, 0xD9));
            _chartLower.View.AxisY.MajorGridStroke = new SolidColorBrush(Color.FromArgb(0xFF, 0xD9, 0xD9, 0xD9));
            _chartLower.View.AxisX.AnnoTemplate = anno;
            _chartLower.View.AxisY.AnnoTemplate = anno;
            _chartLower.View.AxisX.IsTime = true;
            _chartLower.View.AxisX.AnnoFormat = "yyyy";
            _chartLower.View.AxisX.AnnoPosition = AnnoPosition.Near;
            _chartLower.Palette = Palette.Standard;

            // the really cool slider
            _slider = new ChartSlider();
            _slider.ReplacePlaceHolder(chartZoomer, false);

            // scrollbar - needs skinned
            _sb = new C1ScrollBar();
            _sb.IsHorizontal = true;
            _sb.ReplacePlaceHolder(scroll, false);

            // create the default symbols
            CreateSymHolders();

            // -- symbol search box
            _txtbox = new SearchBox();
            _txtbox.ReplacePlaceHolder(cmbSymbolChart, false);
            _txtbox.FontFamily = new FontFamily("Verdana");
            _txtbox.Items = PortfolioSet.Symbols;
            _txtbox.TextWidth = 250;

            // show popup above the control
            _txtbox.Popup.Position = PopupPosition.Below;

            // configure popup color
            C1ListBox lb = _txtbox.Popup.Content as C1ListBox;
            lb.Border.Fill = new SolidColorBrush(Color.FromArgb(255, 230, 230, 250));
            _btnAdd = new ButtonAdd();
            _btnAdd.Click += new EventHandler(_btnAdd_Click);
            _btnAdd.ReplacePlaceHolder(btnAdd2, false);

            // create the zoom buttons
            CreateZoomButtons();

            // show the date range being viewed
            _lblDateRange = new C1Label();
            _lblDateRange.AutoHeight = false;
            _lblDateRange.TextBlock.FontSize = 8;
            _lblDateRange.ReplacePlaceHolder(lblStatus2, false);
            _lblDateRange.Text = string.Empty;
            //_logic = new ChartLogic(this,_chartUpper, _chartLower, _sb, _slider, _symHolder, _lblDateRange);

            // add the charts to the page
            chartMain.Child = _chartUpper;
            chartSub.Child = _chartLower;
            SetClip(chartMain);
            SetClip(chartSub);

            // the dohickey that shows the grid page
            PageBar bar = new PageBar();
            bar.Click += new EventHandler(bar_Click);
            bar.ReplacePlaceHolder(pageBar, false);

            _companyInfo = new CompanyInfo(this);
        }

        void SetClip(FrameworkElement e)
        {
            RectangleGeometry rg = new RectangleGeometry();
            rg.Rect = new Rect(0, 0, e.Width, e.Height);
            e.Clip = rg;
        }
        void _chartUpper_LegendChanged(object sender, EventArgs e)
        {
            if(_logic!=null)
                UpdateSymbols();
        }

        private void CreateSymHolders()
        {
            _symHolder = new C1StackPanel();
            _symHolder.IsHorizontal = true;
            _symHolder.ChildSpacing = new Size(4, 2);
            _symHolder.Padding = new Thickness(5);
            _symHolder.ReplacePlaceHolder(ActiveSymHolder, false);

            ActiveStockButton btn = new ActiveStockButton();
            btn.Text = "Nasd"; btn.Tag = "Nasd";
            btn.Check = false;
            btn.SymbolColor = new SolidColorBrush(Colors.DarkGray);
            btn.CheckedChanged += new EventHandler(btn_CheckedChanged);
            _symHolder.Children.Add(btn);

            btn = new ActiveStockButton();
            btn.Text = "Dow"; btn.Tag = "Dow";
            btn.SymbolColor = new SolidColorBrush(Colors.DarkGray);
            btn.CheckedChanged += new EventHandler(btn_CheckedChanged);
            _symHolder.Children.Add(btn);

            btn = new ActiveStockButton();
            btn.Text = "S&P500"; btn.Tag = "S&P500";
            btn.SymbolColor = new SolidColorBrush(Colors.DarkGray);
            btn.CheckedChanged += new EventHandler(btn_CheckedChanged);
            _symHolder.Children.Add(btn);
        }

        private void CreateZoomButtons()
        {
            _zoomButtons = new C1StackPanel();
            _zoomButtons.IsHorizontal = true;
            _zoomButtons.ReplacePlaceHolder(zBtns, false);

            string[] btns = { "All", "2Y", "1Y", "YTD", "6M", "3M", "1M" };

            _zoomButtons.BeginUpdate();
            for (int i = 0; i < btns.Length; i++)
            {
                ZoomButton btn = new ZoomButton();
                btn.Padding = new Thickness(1);
                btn.Text = btns[i];
                btn.CheckedChanged += new EventHandler(ZoomBtn_CheckedChanged);
                _zoomButtons.Children.Add(btn);
            }
            _zoomButtons.EndUpdate();
        }

        // handles the predefined ranges (e.g., 2Y, 1Y, 6M, etc.)
        void ZoomBtn_CheckedChanged(object sender, EventArgs e)
        {
            ZoomButton btn = (ZoomButton)sender;

            if (btn.Checked)
            {
                // update slider with built in ranges
                _logic.SetTimeRange(btn.Text);

                // update the label with the text of the range
                // _lblDateRange.Text = btn.Text;
            }
        }
        
        void btn_CheckedChanged(object sender, EventArgs e)
        {
            ActiveStockButton btn = (ActiveStockButton)sender;
            if (btn.Check)
            {
                // add the stuff to the chart
                if(btn.Tag is string)
                    _logic.Add((string)btn.Tag);
            }
            else
            {
                // remove the stuff from the chart, leave the button
                if (btn.Tag is string)
                {
                    _logic.Remove((string)btn.Tag);
                    btn.Text = (string)btn.Tag;
                }
            }
            UpdateSymbols();
        }

        void _btnAdd_Click(object sender, EventArgs e)
        {
            // nothing entered
            if (_txtbox.Text.Length == 0) return;

            AddSym(_txtbox.Text);
        }

        void AddSymbol(CurrentStockInfo info)
        {
            _companyInfo._lblName.Text = info._name;
            _companyInfo._lblHigh.Text = info._high.ToString("f");
            _companyInfo._lblLow.Text = info._low.ToString("f");
            _companyInfo._lblOpen.Text = info._open.ToString("f");

            float vol = info._volume / 1000000;
            _companyInfo._lblVolume.Text = vol.ToString("f") + "M";
            _companyInfo._lblSymbol.Text = "Public, NASDAQ: " + info._symbol;
            _companyInfo._lblLastDate.Text  = DateTime.Now.ToString("t");
            _companyInfo._lblLastTrade.Text = ((info._high + info._low) / 2).ToString("f");

            _selectedSym = new ActiveStockButton();
            _selectedSym.Text = info._symbol;
            _selectedSym.Tag = info._symbol;
            _selectedSym.Check = true;
            _selectedSym.Enabled = false;
            _selectedSym.CheckedChanged += new EventHandler(btn_CheckedChanged);

            _symHolder.Children.Insert(0, _selectedSym);

            // update the upper chart with the new stock
            _logic.Add(info._symbol);
            ZoomButton btn = _zoomButtons.Children[3] as ZoomButton;
            btn.Checked = true;
        }
        /// <summary>
        /// Adds a symbol to the chart
        /// </summary>
        /// <param name="sym"></param>
        void AddSym(string sym)
        {
            ActiveStockButton btn = new ActiveStockButton();
            btn.Text = sym;
            btn.Tag = sym;
            btn.Check = true;
            btn.CheckedChanged += new EventHandler(btn_CheckedChanged);
            
            _symHolder.Children.Add(btn);

            // update the upper chart with the new stock

            _logic.Add(sym);
            _logic.UpdateChart(false);
        }

        void btn_DoubleClick(object sender, MouseEventArgs e)
        {
            ActiveStockButton btn = (ActiveStockButton)sender;
            _logic.Remove((string)btn.Tag);
            _symHolder.Children.Remove(btn);
        }

        void bar_Click(object sender, EventArgs e)
        {
            ShowGrid();
            if (_selectedSym != null && _selectedSym.Tag != null)
            {
                int count = _zoomButtons.Children.Count;
                for (int i = 0; i < count; i++)
                {
                    ZoomButton btn = _zoomButtons.Children[i] as ZoomButton;
                    btn.Checked = false;
                }
                _selectedSym.CheckedChanged -= new EventHandler(btn_CheckedChanged);
                _logic.Remove(_selectedSym.Tag.ToString());
                _symHolder.Children.Remove(_selectedSym);
                _selectedSym.Tag = null;
            }
        }

        void UpdateSymbols()
        {
            int cnt = _symHolder.Children.Count;
            for (int i = 0; i < cnt; i++)
            {
                ActiveStockButton btn = _symHolder.Children[i] as ActiveStockButton;
                btn.SymbolColor = new SolidColorBrush(
                    _logic.GetSymbolColor(btn.Tag as string));
            }
        }
    }
}
