using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using DataPerformer;
using DiagramUI;
using ToolBox;
using FormulaEditor;
using FormulaEditorUI;


namespace DataPerformerUI
{
    public partial class FormVectorConsumer : Form, IUpdatableForm
    {

        private VectorFormulaConsumer consumer;
        private IObjectLabel label;
        const string form = "Formula ";



        private FormVectorConsumer()
        {
            InitializeComponent();
        }

        public FormVectorConsumer(IObjectLabel label)
        {
            InitializeComponent();
            ResourceService.Resources.LoadControlResources(this);
            EditorReceiver.AddEditorDrag(panelComments);
            PictureReceiver.AddImageDrag(panelComments);
            this.label = label;
            consumer = label.Object as VectorFormulaConsumer;
            ArrayList comments = consumer.Comments;
            ControlPanel.LoadControls(panelComments, comments);
            checkBoxCalcDeri.Checked = consumer.CalculateDerivation;
            UpdateFormUI();
            List<string> a = consumer.AliasNames;
            string al = "";
            createUnary();
            try
            {
                foreach (string s in a)
                {
                    dataTableP.Rows.Add(new object[] { s, consumer[s] });
                    al += s;
                }
                string str = consumer.AllVariables;
                foreach (char c in str)
                {
                    if (al.IndexOf(c) < 0)
                    {
                        checkedListBoxP.Items.Add("" + c, CheckState.Unchecked);
                    }
                    else
                    {
                        checkedListBoxP.Items.Add("" + c, CheckState.Checked);
                    }
                }
                IMeasurements m = consumer;
                numericUpDownQuantity.Value = m.Count;
                fillFormulas();
                fillComboUnary();
                setComboboxes();
            }
            catch (Exception)
            {
            }
        }

        /// <summary>
        /// Updates form UI
        /// </summary>
        public void UpdateFormUI()
        {
            Text = label.RootName;//NamedComponent.GetText(label);
            string variables = consumer.InputParameters;
            int y = 20;
            for (int i = 0; i < consumer.Count; i++)
            {
                IMeasurements arrow = consumer[i];
                PanelMeasureFormula panel = new PanelMeasureFormula(arrow, variables, consumer);
                panel.Width = 300;
                Panel pan = new Panel();
                pan.Width = panel.Width;
                pan.BackColor = Color.Black;
                pan.Top = y;
                pan.Height = 2;
                panelMea.Controls.Add(pan);
                y += pan.Height;
                panelMea.Controls.Add(panel);
                panel.Left = 0;
                panel.Top = y;
                y += panel.Height + 1;
            }
            if (consumer.Arguments != null)
            {
                foreach (string str in consumer.Arguments)
                {
                    comboBoxTime.Items.Add(str[0] + "");
                }
                foreach (string str in consumer.Arguments)
                {
                    string s = str;
                    int n = str.Length;
                    if (s.Substring(n - 4, 4).Equals("Time"))
                    {
                        for (int i = 0; i < comboBoxTime.Items.Count; i++)
                        {
                            if (comboBoxTime.Items[i].ToString()[0] == str[0])
                            {
                                comboBoxTime.SelectedIndex = i;
                                return;
                            }
                        }
                    }
                }
            }
        }

        public void ResetCombo()
        {
            foreach (Control c in panelMea.Controls)
            {
                if (!(c is PanelMeasureFormula))
                {
                    continue;
                }
                PanelMeasureFormula p = c as PanelMeasureFormula;
                p.ResetCombo();
            }
            comboBoxTime.Items.Clear();
            comboBoxTime.Text = "";
        }

        public DynamicalParameter Parameter
        {
            get
            {
                try
                {
                    DynamicalParameter par = new DynamicalParameter();
                    foreach (Control c in panelMea.Controls)
                    {
                        if (!(c is PanelMeasureFormula))
                        {
                            continue;
                        }
                        PanelMeasureFormula p = c as PanelMeasureFormula;
                        p.CreateArguments(par);
                    }
                    object ob = comboBoxTime.SelectedItem;
                    if (ob != null)
                    {
                        string sn = ob.ToString();
                        if (sn.Length != 0)
                        {
                            IMeasure m = DataConsumer.TimeMeasure;
                            par.Add(sn[0], m);
                        }
                    }

                    return par;
                }
                catch (Exception e)
                {
                    DefaultForm.ShowError(this, e);
                }
                return null;
            }
        }

        public ArrayList Arguments
        {
            get
            {
                ArrayList list = new ArrayList();
                foreach (Control c in panelMea.Controls)
                {
                    if (!(c is PanelMeasureFormula))
                    {
                        continue;
                    }
                    PanelMeasureFormula p = c as PanelMeasureFormula;
                    p.AddArgumentLabels(list);
                }
                object ob = comboBoxTime.SelectedItem;
                if (ob != null)
                {
                    string sn = comboBoxTime.SelectedItem.ToString();
                    if (sn.Length != 0)
                    {
                        list.Add(sn + " = Time");
                    }
                }
                return list;
            }
        }

        private void buttonSetQuantity_Click(object sender, System.EventArgs e)
        {
            int n = (int)numericUpDownQuantity.Value;
            consumer.Dimension = n;
            createFormulaControls();
            ResetCombo();
        }
        private void createFormulaControls()
        {
            ArrayList formulas = new ArrayList();
            foreach (Control c in panelFormula.Controls)
            {
                if (!(c is PanelFormula))
                {
                    continue;
                }
                PanelFormula p = c as PanelFormula;
                formulas.Add(p.Formula);
            }
            panelFormula.Controls.Clear();
            int w = panelFormula.Width;
            int y = 0;
            IMeasurements m = consumer;
            int n = m.Count;
            for (int i = 0; i < n; i++)
            {
                PanelFormula p = new PanelFormula(form + (i + 1), this, panelFormula.Width, 200,
                    "abcdfghijklmnopqrstuvwxyz", false, null, null);
                p.Left = 0;
                p.Top = y;
                y += p.Height;
                if (i < formulas.Count)
                {
                    string formula = formulas[i] as string;
                    p.Formula = formula;
                }
                panelFormula.Controls.Add(p);
            }
        }

        private void fillFormulas()
        {
            panelFormula.Controls.Clear();
            int w = panelFormula.Width;
            int y = 0;
            IMeasurements m = consumer;
            int n = m.Count;
            for (int i = 0; i < n; i++)
            {
                PanelFormula p = new PanelFormula(form + (i + 1), this, panelFormula.Width, 200,
                    "abcdfghijklmnopqrstuvwxyz", false, null, null);
                p.Left = 0;
                p.Top = y;
                y += p.Height;
                panelFormula.Controls.Add(p);
                string f = consumer.GetFormula(i);
                if (f != null)
                {
                    p.Formula = f;
                }
            }
        }

        private void acceptFormulas()
        {
            try
            {
                ResetCombo();
                int i = 0;
                foreach (Control c in panelFormula.Controls)
                {
                    if (!(c is PanelFormula))
                    {
                        continue;
                    }
                    PanelFormula p = c as PanelFormula;
                    consumer.SetFormula(p.Formula, i);
                    ++i;
                }
                consumer.AcceptFormulas();
                checkedListBoxP.Items.Clear();
                string par = consumer.AllVariables;
                foreach (char c in par)
                {
                    checkedListBoxP.Items.Add("" + c);
                }
            }
            catch (Exception e)
            {
                DefaultForm.ShowError(this, e);
            }
        }

        private void buttonAcceptForm_Click(object sender, System.EventArgs e)
        {
            acceptFormulas();
            fillComboUnary();
        }

        private void acceptConstants()
        {
            try
            {
                string str = "";
                Hashtable t = new Hashtable();
                foreach (DataRow row in dataTableP.Rows)
                {
                    string s = row[0] as string;
                    double x = (double)row[1];
                    t[s] = x;
                }
                dataTableP.Rows.Clear();
                foreach (string s in checkedListBoxP.CheckedItems)
                {
                    double a = 0;
                    if (t.ContainsKey(s))
                    {
                        a = (double)t[s];
                    }
                    dataTableP.Rows.Add(new object[] { s, a });
                    str += s;
                }
                consumer.CreateAliases(str);
                string var = consumer.InputParameters;
                foreach (Control c in panelMea.Controls)
                {
                    if (!(c is PanelMeasureFormula))
                    {
                        continue;
                    }
                    PanelMeasureFormula p = c as PanelMeasureFormula;
                    p.FillComboboxes(var);
                }
                comboBoxTime.Items.Clear();
                comboBoxTime.Text = "";
                foreach (char c in var)
                {
                    comboBoxTime.Items.Add(c + "");
                }

            }
            catch (Exception e)
            {
                DefaultForm.ShowError(this, e);
            }
        }
        private void buttonAcceptConst_Click(object sender, System.EventArgs e)
        {
            acceptConstants();
            fillComboUnary();
        }

        private void acceptValues()
        {
            try
            {
                foreach (DataRow row in dataTableP.Rows)
                {
                    string p = (string)row[0];
                    double v = (double)row[1];
                    consumer[p] = v;
                }
            }
            catch (Exception e)
            {
                DefaultForm.ShowError(this, e);
            }
        }

        private void buttonAcceptValues_Click(object sender, System.EventArgs e)
        {
            acceptValues();
        }

        private void acceptParameters()
        {
            consumer.Parameter = Parameter;
            consumer.Arguments = Arguments;
        }

        private void buttonAcceptPar_Click(object sender, System.EventArgs e)
        {
            try
            {
                acceptUnaries();
                acceptParameters();
            }
            catch (Exception ex)
            {
                DefaultForm.ShowError(this, ex);
            }
        }

        private void createUnary()
        {
            panelUnary.Controls.Clear();
            int w = panelUnary.Width;
            int y = 0;
            for (int i = 0; i < consumer.OperationsCount; i++)
            {
                PanelUnary p = new PanelUnary(consumer.GetOperation(i), w);
                p.Left = 0;
                p.Top = y;
                y += p.Height;
                panelUnary.Controls.Add(p);
            }
        }

        private void fillComboUnary()
        {
            ArrayList l = consumer.OperationNumbers;
            foreach (object o in panelUnary.Controls)
            {
                if (!(o is PanelUnary))
                {
                    continue;
                }
                PanelUnary p = o as PanelUnary;
                p.FillComboBoxes(l);
            }
        }
        private void setComboboxes()
        {
            Hashtable table = consumer.OperationNames;
            foreach (object o in panelUnary.Controls)
            {
                if (!(o is PanelUnary))
                {
                    continue;
                }
                PanelUnary p = o as PanelUnary;
                p.SetComboBoxes(table);
            }
        }

        private void acceptUnaries()
        {
            Hashtable table = new Hashtable();
            foreach (object o in panelUnary.Controls)
            {
                if (!(o is PanelUnary))
                {
                    continue;
                }
                PanelUnary p = o as PanelUnary;
                p.FillTable(table);
            }
            consumer.OperationTable = table;
        }

        private void buttonAcceptComments_Click(object sender, System.EventArgs e)
        {
            ArrayList comments = ControlPanel.GetControls(panelComments);
            consumer.Comments = comments;
        }


        private void menuItemFont_Click(object sender, System.EventArgs e)
        {
            try
            {
                TextBox box = ControlPanel.GetActiveTextBox(panelComments);
                if (box == null)
                {
                    return;
                }
                FontDialog dlg = new FontDialog();
                dlg.ShowDialog(this);
                Font font = dlg.Font;
                box.Font = font;
            }
            catch (Exception ex)
            {
                DefaultForm.ShowError(this, ex);
            }
        }

        private void buttonAcceptGraphs_Click(object sender, System.EventArgs e)
        {
            try
            {
                acceptUnaries();
            }
            catch (Exception ex)
            {
                DefaultForm.ShowError(this, ex);
            }
        }

        private void checkBoxCalcDeri_CheckedChanged(object sender, System.EventArgs e)
        {
            consumer.CalculateDerivation = checkBoxCalcDeri.Checked;
        }




    }
}