using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Xml;
using System.Resources;
using System.Collections;



using DiagramUI;
using ToolBox;
using FormulaEditor;
using DataWarehouse;
using DataSetService;
using ResourceService;

namespace Astronomy.UI
{
    public partial class FormMain : Form, IBlob, IErrorHandler
    {

        private PanelDesktop active;
        ToolsDiagram tools;
        AstronomyFactory factory;
        DatabaseInterface data;
        private string text;
        private FormContainerDesigner formContainer;
        string filename = "";

        private FormMain()
        {
            InitializeComponent();
        }

        public FormMain(string[] args)
            : this()
        {
            prepare();
            if (args != null)
            {
                if (args.Length == 1)
                {
                    filename = args[0];
                }
            }
            ResourceService.Resources.LoadControlResources(this);
            text = Text;
        }

        #region IErrorHandler Members

        public void ShowError(Exception e)
        {
            DiagramUI.DefaultForm.ShowError(this, e);
        }

        public void ShowMessage(string message)
        {
            MessageBox.Show(this, message);
        }

        #endregion


        #region LoadSave
        public void SaveAll(Stream stream)
        {
            try
            {
                check();
                active.SaveAll(stream);
                ControlPanel.SaveControls(active, stream);
            }
            catch (Exception ex)
            {
                DiagramUI.DefaultForm.ShowError(this, ex);
            }
        }

        public bool LoadFromStream(Stream stream)
        {

            SerializationBinder[] binders = null;
            PureDesktopPeer d = new PureDesktopPeer();
            bool b = d.Load(stream, binders);
            if (b)
            {
                active.Copy(d.Objects, d.Arrows, true);
                active.Redraw();
                ControlPanel.LoadControls(active, stream, null);
            }
            return b;
        }

        private void check()
        {
            List<Exception> l = PureDesktopPeer.Check(active, null);
            if (l != null)
            {
                throw l[0];
            }
        }
        #endregion

        #region Init

        protected void prepare()
        {
            factory = new AstronomyFactory();
            factory.ErrorHandler = this;
            ResourceService.Resources.CurrentDirectory = Environment.CurrentDirectory + "\\";
            Environment.CurrentDirectory = ResourceService.Resources.CurrentDirectory + "";
            tools = new ToolsDiagram(factory);
            tools.Tree = treeViewObjects;
            // factory.ErrorHandler = this;
            // factory.ProgressIndicator = this;
            ImageList imageListP = new ImageList();
            imageListP.ImageSize = new Size(25, 25);
            imageListP.Images.Add(ResourceImage._object);
            imageListP.Images.Add(ResourceImage.Arrow);





            ImageList imageListOb = new ImageList();
            imageListOb.ImageSize = new Size(25, 25);
            imageListOb.Images.Add(ResourceImage.MultiInterface);
            imageListOb.Images.Add(ResourceImage.Query);
            imageListOb.Images.Add(ResourceImage.DataTableSelection);
            imageListOb.Images.Add(ResourceImage.DataTableIterator);
            imageListOb.Images.Add(ResourceImage.FormulaEditor);
            imageListOb.Images.Add(ResourceImage.RecoursiveGLM);
            imageListOb.Images.Add(ResourceImage.Transform);
            imageListOb.Images.Add(ResourceImage.Graph);
            imageListOb.Images.Add(ResourceImage.Series);
            imageListOb.Images.Add(ResourceImage.SeriesIterator);
            imageListOb.Images.Add(ResourceImage.SeriesData);
            imageListOb.Images.Add(ResourceImage.Dimension);
            imageListOb.Images.Add(ResourceImage.LinearMeasure);
            imageListOb.Images.Add(ResourceImage.DataFrame);
            imageListOb.Images.Add(ResourceImage.Indicator3D);
            imageListOb.Images.Add(ResourceImage.CameraStars);
            imageListOb.Images.Add(ResourceImage.FormulaFilter);
            imageListOb.Images.Add(ResourceImage.Indicator2D);
            imageListOb.Images.Add(ResourceImage.Fuzzy_Dice);
            imageListOb.Images.Add(ResourceImage.Recursive);
            imageListOb.Images.Add(ResourceImage.ODE);
            imageListOb.Images.Add(ResourceImage.palette);
            imageListOb.Images.Add(ResourceImage.AliasRegression);
            imageListOb.Images.Add(ResourceImage.Contour);
            Motion6D.PositionObjectFactory visible = Motion6D.PositionObjectFactory.Factory;
            if (visible != null)
            {
                imageListOb.Images.Add(ResourceImage.Camera);
                imageListOb.Images.Add(ResourceImage.Cube);
            }

            ImageList imageListAr = new ImageList();
            imageListAr.ImageSize = new Size(25, 25);
            imageListAr.Images.Add(ResourceImage.DataLink);
            imageListAr.Images.Add(ResourceImage.DataTableSelectionLink);
            imageListAr.Images.Add(ResourceImage.TransformArrow);
            imageListAr.Images.Add(ResourceImage.UnaryLink);
            imageListAr.Images.Add(ResourceImage.DimensionLink);
            imageListAr.Images.Add(ResourceImage.LinearMeasureLink);
            imageListAr.Images.Add(ResourceImage.Indicator3DLink);
            imageListAr.Images.Add(ResourceImage.IteratorLink);
            imageListAr.Images.Add(ResourceImage.SelectionLink);
            imageListAr.Images.Add(ResourceImage.ContourLink);
            if (visible != null)
            {
                imageListAr.Images.Add(ResourceImage.Eye);
            }


            PaletteToolBar ObjectsToolP = new PaletteToolBar(tools);
            ObjectsToolP.ImageList = imageListP;
            ObjectsToolP.ImageList = imageListP;
            PaletteButton p = new PaletteButton(ObjectsToolP, -2, null, "", "Selection arrow", imageListP.Images[0], 0, true);
            p.Visible = false;

            new PaletteButton(ObjectsToolP, -1, null, "", "Selection arrow", imageListP.Images[1], 1, true);
            panelToolLeft.Controls.Add(ObjectsToolP);


            PaletteToolBar ObjectsToolOb = new PaletteToolBar(tools);
            ObjectsToolOb.ImageList = imageListOb;

            PaletteButton pb = new PaletteButton(ObjectsToolOb, (int)ButtonKinds.MultiLibraryObject, "DiagramUI.MultiLibraryObject", "", ResourceService.Resources.GetResourceString("Multi library"), imageListOb.Images[0], 0, false);
            factory.LibraryButton = pb;
            new PaletteButton(ObjectsToolOb, (int)ButtonKinds.StatementWrapper, "DataSetService.StatementWrapper", "", ResourceService.Resources.GetResourceString("ODBC Table"), imageListOb.Images[1], 1, false);

            new PaletteButton(ObjectsToolOb, (int)ButtonKinds.DataSetSelection, "DataTableSelection.DataSetSelection", "", ResourceService.Resources.GetResourceString("Table selection"), imageListOb.Images[2], 2, false);

            new PaletteButton(ObjectsToolOb, (int)ButtonKinds.DataSetIterator, "DataTableSelection.DataSetIterator", "", ResourceService.Resources.GetResourceString("Data set iterator"), imageListOb.Images[3], 3, false);
            new PaletteButton(ObjectsToolOb, (int)ButtonKinds.VectorFormulaConsumer, "DataPerformer.VectorFormulaConsumer", "Mv", ResourceService.Resources.GetResourceString("Vector perfomer"), imageListOb.Images[4], 4, false);
            new PaletteButton(ObjectsToolOb, (int)ButtonKinds.IteratorGLM, "DataPerformer.IteratorGLM", "", ResourceService.Resources.GetResourceString("Data set iterator"), imageListOb.Images[5], 5, false);
            new PaletteButton(ObjectsToolOb, (int)ButtonKinds.ObjectTransformer, "DataPerformer.ObjectTransformer", "", ResourceService.Resources.GetResourceString("Object transformer"), imageListOb.Images[6], 6, false);
            new PaletteButton(ObjectsToolOb, (int)ButtonKinds.DataConsumer, "DataPerformer.DataConsumer", "", ResourceService.Resources.GetResourceString("Graph representation"), imageListOb.Images[7], 7, false);
            new PaletteButton(ObjectsToolOb, (int)ButtonKinds.Series, "DataPerformer.Series", "", ResourceService.Resources.GetResourceString("Series"), imageListOb.Images[8], 8, false);
            new PaletteButton(ObjectsToolOb, (int)ButtonKinds.SeriesIterator, "DataPerformer.SeriesIterator", "", ResourceService.Resources.GetResourceString("Iterator series"), imageListOb.Images[9], 9, false);
            new PaletteButton(ObjectsToolOb, (int)ButtonKinds.SeriesData, "DataTableSelection.DataTableSeries", "", ResourceService.Resources.GetResourceString("Data table series"), imageListOb.Images[10], 10, false);
            new PaletteButton(ObjectsToolOb, (int)ButtonKinds.RigidReferenceFrame, "Motion6D.RigidReferenceFrame", "", ResourceService.Resources.GetResourceString("Rigig frame"), imageListOb.Images[11], 11, false);
            new PaletteButton(ObjectsToolOb, (int)ButtonKinds.RelativeMeasurements, "Motion6D.RelativeMeasurements", "", ResourceService.Resources.GetResourceString("Relative measurements"), imageListOb.Images[12], 12, false);
            new PaletteButton(ObjectsToolOb, (int)ButtonKinds.ReferenceFrameData, "Motion6D.ReferenceFrameData", "", ResourceService.Resources.GetResourceString("Moved frame"), imageListOb.Images[13], 13, false);
            new PaletteButton(ObjectsToolOb, (int)ButtonKinds.PositionCollectionData, "Motion6D.PositionCollectionData", "", ResourceService.Resources.GetResourceString("Data points collection"), imageListOb.Images[14], 14, false);
            new PaletteButton(ObjectsToolOb, (int)ButtonKinds.PositionCollectionIndicator, "Motion6D.PositionCollectionIndicator", "", ResourceService.Resources.GetResourceString("Points indicator"), imageListOb.Images[15], 15, false);
            new PaletteButton(ObjectsToolOb, (int)ButtonKinds.FormulaFilterIterator, "DataPerformer.FormulaFilterIterator", "", ResourceService.Resources.GetResourceString("Formula filter"), imageListOb.Images[16], 16, false);
            new PaletteButton(ObjectsToolOb, (int)ButtonKinds.DrawSeries, "DataPerformerUI.DrawSeries", "", ResourceService.Resources.GetResourceString("Draw series"), imageListOb.Images[17], 17, false);
            new PaletteButton(ObjectsToolOb, (int)ButtonKinds.Random, "DataPerformer.RandomGenerator", "", ResourceService.Resources.GetResourceString("Random generator"), imageListOb.Images[18], 18, false);
            new PaletteButton(ObjectsToolOb, (int)ButtonKinds.Recursive, "DataPerformer.Recursive", "", ResourceService.Resources.GetResourceString("Recursive"), imageListOb.Images[19], 19, false);
            new PaletteButton(ObjectsToolOb, (int)ButtonKinds.ODE, "DataPerformer.DifferentialEquationSolver", "", ResourceService.Resources.GetResourceString("Differential equation system"), imageListOb.Images[20], 20, false);
            new PaletteButton(ObjectsToolOb, (int)ButtonKinds.DataPicture, "ImageTransformations.DataPicture", "", ResourceService.Resources.GetResourceString("Data picture"), imageListOb.Images[21], 21, false);
            new PaletteButton(ObjectsToolOb, (int)ButtonKinds.AliasRegression, "Regression.AliasRegression", "", ResourceService.Resources.GetResourceString("Regression"), imageListOb.Images[22], 22, false);
            new PaletteButton(ObjectsToolOb, (int)ButtonKinds.BitmapSelection, "ImageNavigation.BitmapSelection", "", ResourceService.Resources.GetResourceString("Image Selection"), imageListOb.Images[23], 23, false);
            int i = 24;
            if (visible != null)
            {
                new PaletteButton(ObjectsToolOb, (int)ButtonKinds.Camera3D, visible.CameraType, "", ResourceService.Resources.GetResourceString("Camera"), imageListOb.Images[i], i, false);
                ++i;
                new PaletteButton(ObjectsToolOb, (int)ButtonKinds.Visible3D, "Motion6D.SerializablePosition", "", ResourceService.Resources.GetResourceString("3D Object"), imageListOb.Images[i], i, false);
                ++i;
            }


            PaletteToolBar ObjectsToolAr = new PaletteToolBar(tools);
            ObjectsToolAr.ImageList = imageListAr;
            new PaletteButton(ObjectsToolAr, (int)ButtonKinds.MeasureLink, "DataPerformer.DataLink", "Mv", ResourceService.Resources.GetResourceString("Measurement consumer link"), imageListAr.Images[0], 0, true);
            new PaletteButton(ObjectsToolAr, (int)ButtonKinds.DataSetArrow, "DataSetService.DataSetArrow", "", ResourceService.Resources.GetResourceString("Link between table provider and table consumer"), imageListAr.Images[1], 1, true);
            new PaletteButton(ObjectsToolAr, (int)ButtonKinds.ObjectTransformerLink, "DataPerformer.ObjectTransformerLink", "", ResourceService.Resources.GetResourceString("Link of object transformer"), imageListAr.Images[2], 2, true);
            new PaletteButton(ObjectsToolAr, (int)ButtonKinds.UnaryLink, "DataPerformer.UnaryLink", "", ResourceService.Resources.GetResourceString("Unary link"), imageListAr.Images[3], 3, true);
            new PaletteButton(ObjectsToolAr, (int)ButtonKinds.ReferenceFrameArrow, "Motion6D.ReferenceFrameArrow", "", ResourceService.Resources.GetResourceString("Geometry link"), imageListAr.Images[4], 4, true);
            new PaletteButton(ObjectsToolAr, (int)ButtonKinds.RelativeMeasurementsLink, "Motion6D.RelativeMeasurementsLink", "", ResourceService.Resources.GetResourceString("Relative measurements link"), imageListAr.Images[5], 5, true);
            new PaletteButton(ObjectsToolAr, (int)ButtonKinds.PositionIndicatorLink, "Motion6D.PositionIndicatorLink", "", ResourceService.Resources.GetResourceString("Points indicator link"), imageListAr.Images[6], 6, true);
            new PaletteButton(ObjectsToolAr, (int)ButtonKinds.IteratorConsumerLink, "DataPerformer.IteratorConsumerLink", "", ResourceService.Resources.GetResourceString("Iterator link"), imageListAr.Images[7], 7, true);
            new PaletteButton(ObjectsToolAr, (int)ButtonKinds.AliasRegressionLink, "Regression.SelectionLink", "", ResourceService.Resources.GetResourceString("Link between selection and selection consumer"), imageListAr.Images[8], 8, true);
            new PaletteButton(ObjectsToolAr, (int)ButtonKinds.BitmapNavigationLink, "ImageNavigation.BitmapMeasurementsLink", "", ResourceService.Resources.GetResourceString("Link between bitmap selection and camera"), imageListAr.Images[9], 9, true);
            i = 10;
            if (visible != null)
            {
                new PaletteButton(ObjectsToolAr, (int)ButtonKinds.VisibleLink, "Motion6D.CameraLink", "", ResourceService.Resources.GetResourceString("Look"), imageListAr.Images[i], i, true);
                ++i;
            }


            this.tabPageObjects.Controls.Add(ObjectsToolOb);
            this.tabPageArrows.Controls.Add(ObjectsToolAr);
            string currDirS = ResourceService.Resources.CurrentDirectory + "";
            /*            StreamReader reader = new StreamReader(currDirS + "Machine");
                        string machineName = reader.ReadLine();
                        EMServer.DatabaseService.MachineName = machineName;
                        EMRemoteClient.RemoteClient.MachineName = machineName;
                        EMDatabaseServer.DataComponent.MachineName = machineName;*/
            active = new PanelDesktop(tools);
            active.Dock = DockStyle.Fill;
            this.panelDesktopCenter.Controls.Add(active);
            active.ResizeImage();
            /*         Active.Top = tabControlTools.Top + tabControlTools.Height + 10;
                     Active.Left = treeViewObjects.Left + treeViewObjects.Width + 10;
                     Active.Width = label1.Left - treeViewObjects.Left - treeViewObjects.Width - 40;
                     Active.Height = Height - Active.Top - 30;
                     treeViewObjects.Height = Height - treeViewObjects.Top - 30;
                     Top = 10;
                     Left = 10;
                     DataPerformer.HeaderControl.Object = ElectromagneticHeaderControl.ThisObject;
                     DataPerformerStrategy.Object = ElectromagneticUI.ElectromagneticStrategy.ThisObject;
                     DataPerformerStrategy.CalculatorCreator =
                         FormulaCalculator.ElementaryFunctionsCalculatorCreator.Object;
                     CategoryTheory.BinaryLoader.Object = new EMDatabaseInterface.DatabaseBinaryLoader();
                     DiagramUI.BinaryChooser.Object = new EMDatabaseInterface.DocumentLoaderChooser();*/
            DataPerformer.DataConsumer.Desktop = active;
            DataSetFactoryChooser.Chooser = ODBCTableProvider.ODBCDataSetFactory.Object;
            DataPerformerUI.HeaderControl.Object = new DataPerformerUI.HeaderControl();
            DataPerformer.DataPerformerStrategy.Object = Motion6D.MovedStrategy.Object;
            initTools();
            initFormEditor();
            initContainers();

            Motion6D.PositionFactory.Factory = MotionUI.ColoredPositionFactory.Object;
            MotionUI.SimpleChooser.Chooser = MotionUI.ColoredChooser.Object;
            DataPerformerUI.SimplePointCollectionChooserFactory.Set();
            Chart.CirclePointFactory.Set();
            DataPerformer.DifferentialEquationProcessor.Object = DataPerformer.RungeProcessor.Processor;
        }


       

        private void initContainers()
        {
            string cont = ResourceService.Resources.CurrentDirectory + "\\Containers.xml";
            if (!File.Exists(cont))
            {
                return;
            }
            XmlDocument doc = new XmlDocument();
            doc.Load(cont);
            XmlNodeList contPages = doc.GetElementsByTagName("Page");
            foreach (XmlElement page in contPages)
            {

                PaletteToolBar ObjectContainers = new PaletteToolBar(tools);
                ObjectContainers.ImageList = new ImageList();
                ObjectContainers.ImageList.ImageSize = new Size(25, 25);
                int np = 0;
                XmlNodeList list = page.GetElementsByTagName("Aggregate");
                foreach (XmlElement el in list)
                {
                    string ico = el.Attributes["icon"].Value;
                    ObjectContainers.ImageList.Images.Add(Image.FromFile(ico));
                    string name = el.Attributes["name"].Value;
                    string hint = el.Attributes["hint"].Value;
                    new PaletteButton(ObjectContainers, (int)ButtonKinds.Container, "DiagramUI.ObjectContainer", name, hint, ObjectContainers.ImageList.Images[np], np, false);
                    ++np;
                }
                XmlAttribute an = page.Attributes["pageName"];
                TabPage tp = new TabPage(an.Value);
                tp.ToolTipText = page.Attributes["pageHint"].Value;
                tabControlControls.Controls.Add(tp);
                tp.Controls.Add(ObjectContainers);
            }

        }

        private void initTools()
        {
            MovedTextBox.MoveImage = ResourceImage.Move;
            EditorReceiver.AddEditorDrag(active);
            PictureReceiver.AddImageDrag(active);
        }

        private void initFormEditor()
        {
            MathSymbolFactory.Sizes = new int[] { 15, 11, 9, 6 };
            FormulaEditorUI.FormulaEditorPanel fp = new FormulaEditorUI.FormulaEditorPanel();
            fp.Prepare();
            string seb = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            string sel = "abcdefghijklmnopqrstuvwxyz";
            string srb = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЬЫЪЭЮЯ";
            string srl = "абвгдеёжзийклмнопрстуфхцчшщьыъэюя";
            string[] sym = new string[] { seb, sel, srb, srl };
            DataPerformerUI.PanelFormula.Symbols = sym;

            // FormulaTree.InitDeri();
            ObjectFormulaTree.Creator = new FormulaArrayObjectCreator(ElementaryFunctionsCreator.Object);
            ElementaryFunctionOperation.InitDeri();
            ElementaryIntegerOperation.Prepare();
        }

        #endregion

        #region Work with files

        private void saveas()
        {
            try
            {
                //check();
                saveFileDialogScn.InitialDirectory = ResourceService.Resources.CurrentDirectory + "scn";
                if (saveFileDialogScn.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
                save(saveFileDialogScn.FileName);
            }
            catch (Exception ex)
            {
                DiagramUI.DefaultForm.ShowError(this, ex);
            }
        }

        private void save(string filename)
        {
            try
            {
                Stream stream = File.Open(filename, FileMode.Create);
                SaveAll(stream);
                stream.Close();
                this.filename = filename;
                setText();
            }
            catch (Exception ex)
            {
                DiagramUI.DefaultForm.ShowError(this, ex);
            }
        }

        private void save()
        {
            if (filename == null)
            {
                saveas();
                return;
            }
            if (filename.Length == 0)
            {
                saveas();
                return;
            }
            save(filename);
        }


        void setText()
        {
            Text = text + " [" + filename + "]";
        }


        void open()
        {
            openFileDialogScn.InitialDirectory = ResourceService.Resources.CurrentDirectory + "scn";
            if (openFileDialogScn.ShowDialog(this) != DialogResult.OK)
            {
                return;
            }
            Stream stream = File.OpenRead(openFileDialogScn.FileName);
            LoadFromStream(stream);
            stream.Close();
            filename = openFileDialogScn.FileName + "";
            setText();
        }


        #endregion


        private void clearallToolStripMenuItem_Click(object sender, EventArgs e)
        {
            active.RemoveAll();
            active.Redraw();
            active.Refresh();

        }

        private void clearselectedToolStripMenuItem_Click(object sender, EventArgs e)
        {
            active.RemoveSelected();
            active.Redraw();
            active.Refresh();

        }

        /*        private void logtestToolStripMenuItem1_Click(object sender, EventArgs e)
                {
                    Form f = new FormTestLog(active);
                    f.Show();
                }
        */

        private void deletecommentsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            active.DeleteComments();
        }


        private void toolStripButtonOpen_Click(object sender, EventArgs e)
        {
            openToolStripMenuItem_Click(sender, e);
        }


        private void toolStripButtonRefresh_Click(object sender, EventArgs e)
        {
            try
            {
                check();
                active.RefreshObjects();
                GC.Collect();
            }
            catch (Exception ex)
            {
                DiagramUI.DefaultForm.ShowError(this, ex);
            }
        }

        private void toolStripButtonToolBox_Click(object sender, EventArgs e)
        {
            FormTools tools = new FormTools();
            tools.Show();
        }

        private void toolStripButtonFont_Click(object sender, EventArgs e)
        {
            try
            {
                TextBox box = ControlPanel.GetActiveTextBox(active);
                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 toolStripButtonClear_Click(object sender, EventArgs e)
        {
            active.DeleteComments();
            active.RemoveAll();
            active.Redraw();
            active.Refresh();

        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            try
            {

                if (filename != null)
                {
                    if (filename.Length != 0)
                    {
                        Stream stream = File.OpenRead(filename);
                        LoadFromStream(stream);
                        stream.Close();
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (filename.Length == 0)
            {
                saveasToolStripMenuItem_Click(sender, e);
                return;
            }
            try
            {
                Stream stream = File.Open(filename, FileMode.Create);
                SaveAll(stream);
                stream.Close();
            }
            catch (Exception ex)
            {
                DiagramUI.DefaultForm.ShowError(this, ex);
            }
        }


        #region IBlob Members

        byte[] IBlob.Bytes
        {
            get
            {
                MemoryStream stream = new MemoryStream();
                SaveAll(stream);
                return stream.GetBuffer();
            }
            set
            {
                MemoryStream stream = new MemoryStream(value);
                LoadFromStream(stream);
            }
        }

        string IBlob.Extention
        {
            get { return "cfa"; }
            set { }
        }

        #endregion

        private void loadfromdatabaseToolStripMenuItem_Click(object sender, EventArgs e)
        {
            loadFromDatabase();
        }

        private string serverPath
        {
            get
            {
                string path = Application.ExecutablePath;
                int n = path.LastIndexOf(Path.DirectorySeparatorChar);
                path = path.Substring(0, n + 1);
                if (path[path.Length - 1] != Path.DirectorySeparatorChar)
                {
                    path += Path.DirectorySeparatorChar;
                }
                path += "server";
                return path;
            }

        }

        private string server
        {
            get
            {
                string path = serverPath;
                if (!File.Exists(path))
                {
                    return null;
                }
                StreamReader r = new StreamReader(path);
                string s = r.ReadLine();
                r.Close();
                return s;
            }
        }

        private bool prepareData()
        {
            if (data != null)
            {
                return true;
            }
            try
            {
                string ser = server;
                if (ser == null)
                {
                    ser = connect;
                    if (ser == null)
                    {
                        return false;
                    }
                }
                IDatabaseInterface inter = //ReportingServer.ReportingInterface.GetService("");
                    AstronomyDB.AstronomyWarehouse.GetInterface(ser);
                    
                IUser user = new User("", "");
                data = new DatabaseInterface(user, inter);
                AstronomyFactory.Data = data;
                return true;
            }
            catch (Exception e)
            {
                // loadfromdatabaseToolStripMenuItem.Visible = false;
                // savetodatabaseToolStripMenuItem.Visible = false;
                /*toolStripButtonLoadFromDatabase.Visible = false;
                databaseToolStripMenuItem.Visible = false;*/
            }
            return false;
        }


        private string connect
        {
            get
            {
                Form f = new FormCreationInformation();
                if (f.ShowDialog(this) != DialogResult.OK)
                {
                    return null;
                }
                FormConnectToDatabase form = new FormConnectToDatabase();
                form.ShowDialog(this);
                string server = form.Server;
                StreamWriter w = new StreamWriter(serverPath);
                w.Write(server);
                w.Close();
                return server;
            }
        }

 
        private void toolStripButtonLoadFromDatabase_Click(object sender, EventArgs e)
        {
            loadFromDatabase();
        }


        void loadFromDatabase()
        {
            if (!prepareData())
            {
                return;
            }
            try
            {
                FormDatabase form = new FormDatabase(this, data, true);
                form.ShowDialog(this);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }


        private void savetodatabaseToolStripMenuItem_Click(object sender, EventArgs e)
        {
            saveToDatabase();
        }

        void saveToDatabase()
        {
            if (!prepareData())
            {
                return;
            }
            FormDatabase form = new FormDatabase(this, data, false);
            form.ShowDialog(this);
        }

        private void databaseToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!prepareData())
            {
                return;
            }
            FormDatabase form = new FormDatabase(
                new StandardStarter(ResourceService.Resources.CurrentDirectory + "Temp\\"),
                data, true);
            form.ShowDialog(this);
        }

        private void changeorderofselectedToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form form = new FormOrder(active);
            form.ShowDialog(this);

        }

        private void updateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                DataPerformer.DataPerformerStrategy.Object.PrepareAll(active);
                DataPerformer.DataPerformerStrategy.Object.StartAll(active);
                DataPerformer.DataPerformerStrategy.Object.Time = startTime;
                DataPerformer.DataPerformerStrategy.Object.UpdateAll(active);
            }
            catch (Exception ex)
            {
                ShowError(ex);
            }

        }

        private void toolStripButtonSync_Click(object sender, EventArgs e)
        {
            updateToolStripMenuItem_Click(sender, e);
        }

        private void buttonSetThread_Click(object sender, EventArgs e)
        {
        }

        private void buttonStart_Click(object sender, EventArgs e)
        {
            try
            {
                factory.Start(startTime, Int32.Parse(textBoxStartStep.Text), Int32.Parse(textBoxPause.Text),
                    Double.Parse(textBoxStep.Text), Int32.Parse(textBoxSteps.Text), active);
            }
            catch (Exception ex)
            {
                ShowError(ex);
            }
        }



        private double startTime
        {
            get
            {
                return Double.Parse(textBoxStart.Text);
            }
        }

        private void openToolStripButton_Click(object sender, EventArgs e)
        {
            open();
        }

        private void copyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Stream stream = new MemoryStream();
            active.SaveSelected(stream);
            Clipboard.SetData("AstroFrame", stream);
        }

        private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            object o = Clipboard.GetData("AstroFrame");
            if (o == null)
            {
                return;
            }
            Stream stream = o as Stream;
            LoadFromStream(stream);
        }

        private void cutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            clearselectedToolStripMenuItem_Click(sender, e);
        }

        private void saveasToolStripMenuItem_Click(object sender, EventArgs e)
        {
            saveas();
        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            open();
        }

        private void saveToolStripButton_Click(object sender, EventArgs e)
        {
            save();
        }

        private void derivationCalculatorToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form f = new DataPerformerUI.FormDerivationCalculator("xyzt");
            f.Show();
        }

        private void containerDesignerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            showContainerDesigner();
        }

        private void showContainerDesigner()
        {
            if (formContainer == null)
            {
                formContainer = new FormContainerDesigner(active);
            }
            else
            {
                if (formContainer.IsDisposed)
                {
                    formContainer = new FormContainerDesigner(active);
                }
            }
            formContainer.Show();
        }

        static private void localizeRu()
        {
            System.Resources.ResourceManager man = Astronomy.UI.ResourceControl_Ru.ResourceManager;
            localize(man);
            //  ResourceControl_Ru.b
        }


        static private void localize(System.Resources.ResourceManager man)
        {
            Dictionary<string, string> d = new Dictionary<string, string>();
            ResourceSet rs = man.GetResourceSet(System.Globalization.CultureInfo.InvariantCulture, true, false);
            IDictionaryEnumerator rEnu = rs.GetEnumerator();
            while (rEnu.MoveNext())
            {
                string k = rEnu.Key + "";
                k = reverseTransform(k);
                object v = rEnu.Value;
                Resources.ControlResources[k] = v;
            }
        }




        static string reverseTransform(string str)
        {
            string s = str + "";
            s = s.Replace("DEFIS", "-");
            s = s.Replace("_", " ");
            s = s.Replace("AND", "&");
            s = s.Replace("POINT", ".");
            s = s.Replace("MORE", ">");
            s = s.Replace("LESS", "<");
            s = s.Replace("BRA", "(");
            s = s.Replace("KET", ")");
            s = s.Replace("OR", "|");
            s = s.Replace("COMMA", ",");
            s = s.Replace("EQUALS", "=");
            s = s.Replace("APOSTROFF", "'");
            s = s.Replace("STAR", "*");
            s = s.Replace("COLON", ":");
            s = s.Replace("FRACTION", "/");
            s = s.Replace("THREE", "3");
            return s;
        }

        static private void loadResources()
        {
            createResourses();

            string sApp = Resources.CurrentDirectory;
            System.Globalization.CultureInfo c = System.Globalization.CultureInfo.CurrentCulture;
            if (c.TwoLetterISOLanguageName.ToLower().Equals("ru"))
            {
                localizeRu();
            }
        }


        static void createRes(Dictionary<string, string> res)
        {
            Stream stream = File.OpenWrite("1");
            ResourceWriter rw = new ResourceWriter(stream);

            XmlDocument doc = new XmlDocument();
            doc.LoadXml("<Root/>");
            foreach (string key in res.Keys)
            {
                XmlElement e = doc.CreateElement("data");
                doc.DocumentElement.AppendChild(e);
                string s = key;
                s = s.Replace("-", "DEFIS");
                s = s.Replace(" ", "_");
                s = s.Replace("&", "AND");
                s = s.Replace(".", "POINT");
                s = s.Replace(">", "MORE");
                s = s.Replace("<", "LESS");
                s = s.Replace("(", "BRA");
                s = s.Replace(")", "KET");
                s = s.Replace("|", "OR");
                s = s.Replace(",", "COMMA");
                s = s.Replace("=", "EQUALS");
                s = s.Replace("'", "APOSTROFF");
                s = s.Replace("*", "STAR");
                s = s.Replace(":", "COLON");
                s = s.Replace("/", "FRACTION");
                s = s.Replace("3", "THREE");

                rw.AddResource(s, res[key]);
                XmlAttribute a = doc.CreateAttribute("name");
                a.Value = s;
                e.Attributes.Append(a);
                a = doc.CreateAttribute("xml:space");
                a.Value = "preserve";
                e.Attributes.Append(a);
                XmlElement el = doc.CreateElement("value");
                e.AppendChild(el);
                el.InnerText = TransformEncoding(res[key]);
            }
            doc.Save("1.xml");
        }


        static void createRes(string[,] res)
        {
            Dictionary<string, string> r = new Dictionary<string, string>();
            for (int i = 0; i < res.GetLength(0); i++)
            {
                r[res[i, 0]] = res[i, 1];
            }
            createRes(r);
        }

        static private void loadFormulaResources()
        {
            string[,] contents = new string[,]{
                { "s", "sin" },
                { "c", "cos" },
                { "l", "ln" },
                { "u", "lg" },
                { "e", "exp" },
                { "t", "tg" },
                { "q", "ctg"},
                { "a", "arctg" },
                { "b", "arcctg"},
                { "j", "sec" },
                { "k", "cosec" },
                { "f", "arcsin" },
                { "g", "arccos" },
                { "v", "arctg" },
                {"atan2", "atan2"},
                { ".", "," },
                { "+", "+" },
                { "-", "-" },
                { "*", "\u2219" },

                                                      {"\u2260", "\u2260"},	//NE
                                                      {"\u2264", "\u2264"}, //LE
                                                      {"\u2265", "\u2265"}, //GE
                                                      {"\u2217", "OR"}, //Dis
                                                      {"\u2216", "AND"}, //Con
                    {"\u2270", "LIKE"},
                                                      {"¬", "¬"},
                                                      {"~", "~"},
                                                      {"=", "="},
                                                      {">", ">"},
                                                      {"<", "<"},
                                                      {"?", "?"},
                                                      {":", ":"},
                                                      {"&", "&"},
                                                      {"|", "|"},
                                                      {"\u2266", "<<"},
                                                      {"\u2267", ">>"},
                                                      {"^", "^"},
                { "(", "(" },
                { ")", ")" },
                { "1", "1" },
                { "2", "2" },
                { "3", "3" },
                { "4", "4" },
                { "5", "5" },
                { "6", "6" },
                { "7", "7" },
                { "8", "8" },
                { "9", "9" },
                { "0", "0" },
                {"\u2211", "\u2211"}

                };
            MathFormula.Resources = new Hashtable();
            for (int i = 0; i < contents.GetLength(0); i++)
            {
                MathFormula.Resources[contents[i, 0]] = contents[i, 1];
            }

        }


        private static void createResourses()
        {
            loadFormulaResources();

        }

        static public string TransformEncoding(string s)
        {
            string per = "ÀÁÂÃÄÅ¨ÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÜÛÚÝÞßàáâãäå¸æçèéêëìíîïðñòóôõöøùüûúýþÿ";
            string rus = "\u0410\u0411\u0412\u0413\u0414\u0415\u0401\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042C\u042B\u042A\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0451\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0448\u0449\u044C\u044B\u044A\u044D\u044E\u044F";
            string str = "";
            for (int i = 0; i < s.Length; i++)
            {
                char c = s[i];
                int j = per.IndexOf(c);
                if (j > -1)
                {
                    c = rus[j];
                }
                str += c;
            }
            return str;
        }
        static public void LoadResources()
        {
            loadResources();
        }

    }
}


