using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.IO;


using ResourceService;


namespace DataWarehouse
{
    public partial class FormDatabase : Form
    {
        IBlob blob;
        DatabaseInterface data;
        bool open;
        string[] ext;
        private DatabaseNode root;
        private DatabaseNode selectedNode;
        private XmlElement selected;

        static public readonly string DoYowWantDelete = "Do you really want delete ";
        static public readonly string DoYowWantReplace = "Do you really want replace ";



        private FormDatabase()
        {
            InitializeComponent();
        }

        public FormDatabase(IBlob blob, DatabaseInterface data, bool open)
        {
            InitializeComponent();
            Resources.LoadControlResources(this);
            this.blob = blob;
            this.data = data;
            this.open = open;
            ext = new string[] { blob.Extention };
            //labelFileName.Visible = false;
            if (open)
            {
                buttonCreateDir.Enabled = false;
                buttonChangeNodeDescr.Enabled = false;
                buttonSaveDoc.Visible = false;
                //textBoxDescription.Visible = false;
                //textBoxDirDescr.Visible = false;
                //textBoxDirName.Visible = false;
                //textBoxName.Visible = false;
                //buttonSaveDoc.Visible = false;
                buttonReplace.Enabled = false;

            }
            else
            {
                buttonLoad.Visible = false;
            }
            buttonDelete.Enabled = false;
            buttonDirDelete.Enabled = false;
            buttonLoad.Enabled = false;
            refreshTree();
        }


        private void refreshTree()
        {
            XmlDocument doc = data.GetTree(ext);

            XmlElement e = doc.GetElementsByTagName("BinaryNode").Item(0) as XmlElement;
            root = new DatabaseNode(e, "BinaryNode", "BinaryNodeId", "BinaryNodeName", "Binary");
            treeViewDir.Nodes.Add(root);
            treeViewDir.Refresh();
            if (listViewDoc.Items.Count > 0)
            {
                listViewDoc.Items.Clear();
            }
            this.buttonDelete.Enabled = false;
            buttonLoad.Enabled = false;
            this.buttonDirDelete.Enabled = false;
            this.buttonDirDelete.Enabled = false;
        }

        private void treeViewDir_AfterSelect(object sender, TreeViewEventArgs e)
        {
            TreeNode node = treeViewDir.SelectedNode;
            if (node == selectedNode | node == null)
            {
                return;
            }
            selectedNode = node as DatabaseNode;
            if (selectedNode == root)
            {
                buttonDirDelete.Enabled = false;
                buttonSaveDoc.Enabled = false;
                buttonChangeNodeDescr.Enabled = false;
            }
            else
            {
                buttonDirDelete.Enabled = true;
                buttonSaveDoc.Enabled = true;
                buttonChangeNodeDescr.Enabled = true;
            }
            string description = selectedNode.Description;
            labelDirectoryDescr.Text = description;
            if (listViewDoc.Items.Count > 0)
            {
                listViewDoc.Items.Clear();
            }
            refreshTable();

        }

        private void refreshTable()
        {
            if (selectedNode == null)
            {
                return;
            }
            listViewDoc.Items.Clear();
            /*
            if (dataTableDoc.Rows.Count > 0)
            {
                dataTableDoc.Clear();
            }*/
            for (int i = 0; i < selectedNode.ChildrenCount; i++)
            {
                XmlElement el = selectedNode.GetChild(i);
                string name = el.Attributes["BinaryName"].Value;
                string[] s = new string[] { name, el.Attributes["Ext"].Value };
                ListViewItem it = new ListViewItem(s);
                it.Tag = el;
                listViewDoc.Items.Add(it);
            }
            labelDescr.Text = "";
            buttonDelete.Enabled = false;
            buttonLoad.Enabled = false;
        }

        private void treeViewDir_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
        {
            if (e.Label == null)
            {
                return;
            }
            string id = selectedNode.UID;
            data.UpdateData(id, e.Label, labelDescr.Text);
        }

        private void listViewDoc_Click(object sender, EventArgs e)
        {
            if (selectedNode == null)
            {
                return;
            }
            if (listViewDoc.SelectedItems.Count == 0)
            {
                return;
            }
            XmlElement s = listViewDoc.SelectedItems[0].Tag as XmlElement;
            if (selected == s)
            {
                return;
            }
            selected = s;
            if (selected != null)
            {
                XmlElement el = selected.GetElementsByTagName("Description")[0] as XmlElement;
                string desc = el.InnerText;
                labelDescr.Text = desc;
                textBoxDescription.Text = desc;
                buttonDelete.Enabled = true;
                buttonLoad.Enabled = true;
            }

        }

        private void buttonCreateDir_Click(object sender, EventArgs e)
        {
            try
            {
                if (selectedNode == null)
                {
                    return;
                }
            /*    if (textBoxDirName.Text.Length > textLength)
                {
                }*/
                DatabaseNode node = selectedNode;
                string id = node.UID;
                string descr = "";
                foreach (string s in textBoxDirDescr.Lines)
                {
                    descr += s;
                    descr += " ";
                }
                //CheckNameLength(textBoxDirName.Text, descr);
                string sid = data.AddDirectory(id, textBoxDirName.Text, descr, blob.Extention);
                new DatabaseNode(node, sid, textBoxDirName.Text, descr);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void buttonDirDelete_Click(object sender, EventArgs e)
        {
            try
            {
                DatabaseNode selected = selectedNode;
                if (selected == null | selected == root)
                {
                    return;
                }
                DialogResult res = MessageBox.Show(
                    ResourceService.Resources.GetResourceString(DoYowWantDelete) +
                    "\"" + selected.Text + "\"" + "?", "",
                    MessageBoxButtons.OKCancel, MessageBoxIcon.None, MessageBoxDefaultButton.Button1,
                    MessageBoxOptions.DefaultDesktopOnly);
                if (res != DialogResult.OK)
                {
                    return;
                }
                string guid = selected.UID;
                data.RemoveDirectory(guid);
                TreeNode p = selected.Parent;
                if (p.Nodes.Count == 1)
                {
                    treeViewDir.SelectedNode = p;
                }
                selected.Remove();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }


        }

        private void buttonRefresh_Click(object sender, EventArgs e)
        {
            refreshTree();
        }

        private void buttonReplace_Click(object sender, EventArgs e)
        {
            if (selected == null)
            {
                return;
            }
            string guid = selected.Attributes["BinaryId"].Value;
            DialogResult res = MessageBox.Show(
                ResourceService.Resources.GetResourceString(DoYowWantReplace) +
                "\"" + selected.Attributes["BinaryName"].Value + "\"" + "?", "",
                MessageBoxButtons.OKCancel, MessageBoxIcon.None, MessageBoxDefaultButton.Button1,
                MessageBoxOptions.DefaultDesktopOnly);
            if (res != DialogResult.OK)
            {
                return;
            }
            byte[] b = null;
            if (labelFileName.Text.Length != 0)
            {
                Stream stream = File.OpenRead(labelFileName.Text);
                b = new byte[stream.Length];
                stream.Read(b, 0, b.Length);
                stream.Close();
            }
            else
            {
                b = blob.Bytes;
            }
            try
            {
                data.UpdateData(guid, b);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            /*string guid = selected.Attributes["BinaryID"].Value;
            MemoryStream mStream = new MemoryStream();
            parent.SaveAll(mStream);
            int length = (int)mStream.Length;
            byte[] buffer = mStream.GetBuffer();
            DatabaseInterface.DatabaseClient.Service.UpdateBinaryData(guid, buffer);
            mStream.Close();*/
            //DatabaseInterface.DatabaseClient.Service.UpdateBinaryDataTable();
            //DatabaseInterface.DatabaseClient.Service.updateBinaryData();

        }

        private void buttonLoad_Click(object sender, EventArgs e)
        {
            if (selected == null)
            {
                return;
            }
            string guid = selected.Attributes["BinaryId"].Value;
            string ext = "";
            byte[] b = data.GetData(guid, ref ext);
            Close();
            blob.Extention = ext;
            blob.Bytes = b;
        }

        private void buttonSaveDoc_Click(object sender, EventArgs e)
        {
            try
            {
                if (selectedNode == null)
                {
                    return;
                }
                string guid = selectedNode.UID;
                byte[] b = null;
                string ext = "";
                if (labelFileName.Text.Length != 0)
                {
                    Stream stream = File.OpenRead(labelFileName.Text);
                    b = new byte[stream.Length];
                    stream.Read(b, 0, b.Length);
                    stream.Close();
                    int n = labelFileName.Text.LastIndexOf('.');
                    if (n > 0)
                    {
                        ext = labelFileName.Text.Substring(n + 1);
                    }
                }
                else
                {
                    b = blob.Bytes;
                    ext = blob.Extention;
                }
                data.AddData(guid, textBoxName.Text, textBoxDescription.Text, b, ext);
                Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void buttonDelete_Click(object sender, EventArgs e)
        {
            try
            {
                if (selected == null)
                {
                    return;
                }
                string guid = selected.Attributes["BinaryId"].Value;
                string name = selected.Attributes["BinaryName"].Value;
                DialogResult res = MessageBox.Show(
    ResourceService.Resources.GetResourceString(DoYowWantDelete) +
    "\"" + name + "\"" + "?", "",
    MessageBoxButtons.OKCancel, MessageBoxIcon.None, MessageBoxDefaultButton.Button1,
    MessageBoxOptions.DefaultDesktopOnly);
                if (res != DialogResult.OK)
                {
                    return;
                }

                data.RemoveData(guid);
                XmlElement el = selected.ParentNode as XmlElement;
                //el.RemoveChild(selected);
                selectedNode.Remove(selected);
                refreshTable();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (ext == null)
            {
                openFileDialogData.Filter = "|*.*";
            }
            else
            {
                openFileDialogData.Filter = "|*." + ext[0];
            }
            if (openFileDialogData.ShowDialog(this) != DialogResult.OK)
            {
                return;
            }
            labelFileName.Text = openFileDialogData.FileName + "";
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (selected == null)
            {
                return;
            }
            string guid = selected.Attributes["BinaryId"].Value;
            string ext = "";
            byte[] b = data.GetData(guid, ref ext);
            saveFileDialogData.Filter = "|*." + ext;
            saveFileDialogData.FileName = selected.Attributes["BinaryName"].Value;
            if (saveFileDialogData.ShowDialog(this) != DialogResult.OK)
            {
                return;
            }
            Stream stream = File.OpenWrite(saveFileDialogData.FileName);
            stream.Write(b, 0, b.Length);
            stream.Close();
        }

        private void toolStripButtonCreateDir_Click(object sender, EventArgs e)
        {
            buttonCreateDir_Click(sender, e);
        }

        private void toolStripButtonDeleteFolder_Click(object sender, EventArgs e)
        {
            buttonDirDelete_Click(sender, e);
        }

        private void toolStripButtonDelete_Click(object sender, EventArgs e)
        {
            buttonDelete_Click(sender, e);
        }

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

        }

 
    }
}