using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using System.Xml;
using C1.FlexPivot;

namespace ControlExplorer.FlexPivot
{
    public partial class Overview : C1DemoForm
    {
        Timer _timer;
        string dataPath = Path.Combine(System.Windows.Forms.Application.StartupPath, "Data");

        public Overview()
        {
            InitializeComponent();
            labelStatus.Font = new Font(labelStatus.Font, FontStyle.Bold);

            // initialize timer 
            _timer = new Timer();
            _timer.Tick += timer_Tick;
            _timer.Interval = 1000;

            // where DataEngine data is stored
            c1FlexPivotPage1.FlexPivotPanel.Workspace.Init(dataPath);

            
            // build menu with FlexPivot views
            XmlDocument views = new XmlDocument();
            views.LoadXml(ControlExplorer.Properties.Resources.FlexPivotViews);
            foreach (XmlNode nd in views.SelectNodes("FlexPivotViews/C1FlexPivot"))
                comboBox1.Items.Add(nd.Attributes["id"].Value);

            // show update log
            c1FlexPivotPage1.FlexPivotEngine.StartUpdating += FlexPivotEngine_StartUpdating;
            c1FlexPivotPage1.Updated += c1FlexPivotPage1_Updated;
        }

        // generate data
        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            _timer.Enabled = true;
        }

        protected override void Dispose(bool disposing)
        {
            // remove data generated by the C1 DataEngine
            try
            {
                Directory.Delete(dataPath, true);
            }
            catch { }

            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        // generate data
        void timer_Tick(object sender, EventArgs e)
        {
            // disable timer
            _timer.Enabled = false;

            // generate additional rows
            Cursor = Cursors.WaitCursor;
            string tableName = GenerateRows(1000000);
            
            // connect to data
            c1FlexPivotPage1.FlexPivotPanel.ConnectDataEngine(tableName);

            // set default view
            comboBox1.SelectedIndex = 0; 
            Cursor = Cursors.Default;
        }

        // change predefined view
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            c1FlexPivotPage1.FlexPivotEngine.BeginUpdate();

            //set predefined view
            XmlDocument views = new XmlDocument();
            views.LoadXml(ControlExplorer.Properties.Resources.FlexPivotViews);
            XmlNode nd = views.SelectSingleNode(string.Format("FlexPivotViews/C1FlexPivot[@id='{0}']", comboBox1.SelectedItem));
            c1FlexPivotPage1.FlexPivotPanel.ViewDefinition = nd.OuterXml;

            // set lookups
            FillLookup("Country", "LookupCountry");
            FillLookup("Product", "LookupProduct");
            FillLookup("Customer", "LookupCustomer");
            FillLookup("Employee", "LookupEmployee");
            FillLookup("Category", "LookupCategory");

            // update
            c1FlexPivotPage1.FlexPivotEngine.EndUpdate();
        }

        // show status
        void FlexPivotEngine_StartUpdating(object sender, EventArgs e)
        {
            labelStatus.Text = "Analyzing....";
        }

        // hide status
        void c1FlexPivotPage1_Updated(object sender, EventArgs e)
        {
            labelStatus.Text = string.Empty;
        }

        // generate additional rows, to show that C1FlexPivot can handle large data sets
        private string GenerateRows(int count)
        {
            // get predefined source data
            DataTable table = DemoDataSource("Sales");
            
            // remove column protection
            foreach (DataColumn col in table.Columns)
                col.ReadOnly = false;

            // read data from first rows
            int max = table.Rows.Count;
            object[] rd = new object[max];
            for (int i = 0; i < max; i++)
                rd[i] = table.Rows[i].ItemArray;

            // add data to the end of the table
            for (int i = 0; i < count; i += max)
            {
                for (int k = 0; k < max && (k + i) < count; k++)
                {
                    DataRow r = table.NewRow();
                    r.ItemArray = (object[])rd[k];
                    table.Rows.Add(r);
                }
            }
            string tableName = Guid.NewGuid().ToString();
            C1.DataEngine.DbConnector.GetData(c1FlexPivotPage1.FlexPivotPanel.Workspace, table, tableName);
            return tableName;
        }

        // set field lookup
        void FillLookup(string fieldName, string lookupName)
        {
            C1FlexPivotField field = c1FlexPivotPage1.FlexPivotPanel.FlexPivotEngine.Fields[fieldName];
            if (field.Lookup == null)
                field.Lookup = GetLookup(lookupName);
        }

        // create a dictionary from two columns data
        Dictionary<object, string> GetLookup(string name)
        {
            var dict = new Dictionary<object, string>();
            DataTableReader reader = DemoDataSource(name).CreateDataReader();
            while (reader.Read())
                dict.Add(reader.GetValue(0), reader.GetString(1));
            reader.Close();
            return dict;
        }
    }
}
