using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using Newtonsoft.Json;


namespace CobXmlSupport
{
    public partial class ShowCode : Form
    {

        private GenCobCode parentWindow=null;

        public readonly string CSV = ".csv";
        public readonly string DIF = ".dif";
        public readonly string JSON = ".json";

        string oldTxt;
        bool bSynch;
        string finalFileSafe;
        string wholeFilePath;
        string existing = "";

        public savedFile SavedFile { get; set; }

        public ShowCode()
        {
            InitializeComponent();
            oldTxt = "";
            bSynch = false;
            btnMoveToLib.Enabled = false;
        }

        public bool BSynch
        {
            get
            {
                return bSynch;
            }
            set
            {
                bSynch = value;
                btnSynch.Visible = bSynch;
                btnSynchOut.Visible = bSynch;
            }
        }

        public TextBox CodeShower
        {
            get { return txtCode; }
            set { txtCode = value; }
        }

        public string Labeltext
        {
            get { return wholeFilePath; }
            set
            {
                wholeFilePath = value;
                txtCodeType.Text = wholeFilePath.Substring(wholeFilePath.LastIndexOf("\\") + 1); ;
            }
        }


        public GenCobCode FormParent
        {
            get { return parentWindow; }
            set { parentWindow = value; }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void txtCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.A)
            {
                txtCode.SelectAll();
            }
        }

        private void txtCode_TextChanged(object sender, EventArgs e)
        {
            if (txtCode.Text.Length > oldTxt.Length)
            {
                string tmpNewText = txtCode.Text.Substring(oldTxt.Length);

                //Debug.Write(tmpNewText);
                //Tag bort denna kommentering för att testa på vad som precis skrivs på log-fönster.
                oldTxt = txtCode.Text;
            }
        }

        private void btnSynch_Click(object sender, EventArgs e)
        {
            codeCompleter Cc = new codeCompleter(parentWindow.CmbLastFile.Text, parentWindow.FldPref);
            string fieldCompl = "";
            this.CodeShower.Text = " InPath = " +
                Cc.PathId + "\r\n InFile = " +
                Cc.FileId + "\r\n codeFile = " +
                Cc.CcFileInId + "\r\n codePath = " +
                Cc.PathId +
                Cc.CcFileInId + "\r\n -------------- \r\n" +
                this.CodeShower.Text;

            Cc.TryFill_In_Dic();

            foreach (CobRow cr in parentWindow.RowList)
            {
                if (!cr.isAttribute && !cr.SampleStr.Equals(parentWindow.NOMOVE))
                {
                    if (Cc.WorkDicIn != null && Cc.WorkDicIn.Count > 0)
                    {
                        if (Cc.WorkDicIn.TryGetValue(cr.FieldName, out fieldCompl))
                        {
                            cr.MoveCode = fieldCompl;
                        }
                    }
                    if (cr.MoveCode == null) { cr.MoveCode = " "; }
                    Cc.WorkDicIn[cr.FieldName] = cr.MoveCode;
                }
            }

            if (DialogResult.OK == MessageBox.Show("Vill du verkligen spara...?", "Spara kompletterad kod", MessageBoxButtons.OKCancel))
            {
                Cc.Save_In_Dic();
            }

            refreshWindow("IN");

            this.CodeShower.Text = " InPath = " + 
                Cc.PathId + "\r\n InFile = " + 
                Cc.FileId + "\r\n codeFile = " + 
                Cc.CcFileInId + "\r\n codePath = " + 
                Cc.PathId + 
                Cc.CcFileInId + "\r\n -------------- \r\n" + this.CodeShower.Text;

        }

        private Dictionary<string, string> moveJsonFieldDictionary(string ccIn)
        {
            Dictionary<string, string> tmpDic = JsonConvert.DeserializeObject<Dictionary<string, string>>(ccIn);
            return tmpDic;
        }

        private string createJsonFromDic(Dictionary<string, string> wrkDic)
        {
            string tmpJson = JsonConvert.SerializeObject(wrkDic);
            return tmpJson;
        }

        private string deQuote(string inString)
        {
            string tmpStr = "";
            char[] x = inString.ToArray<char>();
            for (int i = 0; i < x.Length; i++)
            {
                if (x[i] == '\"')
                {
                    if (i < x.Length - 1)
                    {
                        if (x[i + 1] == '\"')
                        {
                            i++;
                            tmpStr += "\"";
                        }
                    }
                }
                else tmpStr += x[i];
            }
            return tmpStr;
        }

        private string enQuote(string inString)
        {
            string tmpStr = "";
            char[] x = inString.ToArray<char>();
            for (int i = 0; i < x.Length; i++)
            {
                if (x[i] == '\"')
                {
                    {
                        tmpStr += "\"\"";
                    }
                }
                else tmpStr += x[i];
            }
            return "\"" + tmpStr + "\"";
        }


        private Dictionary<string, string> moveFieldDictionary(string inFil)
        {
            Dictionary<string, string> tmpDic = new Dictionary<string, string>();
            string[] splits = { "\r\n" };
            string[] itemPairs = inFil.Split(splits, StringSplitOptions.RemoveEmptyEntries);
            char[] newSplits = { '\t' };
            foreach (string itemPair in itemPairs)
            {
                string[] items = itemPair.Split(newSplits);
                tmpDic.Add(items[0], items[1].Replace("\n", "\r\n"));
            }

            return tmpDic;
        }

        private Dictionary<string, string> moveDifFieldDictionary(string inFil)
        {
            bool TABLE = false, VECTORS = false, TUPLES = false, DATA = false;
            int rows = 0, rowCount = 0;
            Dictionary<string, string> tmpDic = new Dictionary<string, string>();
            string[] splits = { "\r\n" };
            char[] csplit = { ',' };
            string[] items = inFil.Split(splits, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < items.Count(); i++)
            {
                string item = items[i];
                switch (item.ToUpper())
                {
                    case "TABLE":
                        {
                            TABLE = true;
                            break;
                        }
                    case "VECTORS":
                        {
                            VECTORS = true;
                            string[] nums = items[i + 1].Split(csplit);
                            rows = int.Parse(nums[1]);
                            break;
                        }
                    case "TUPLES":
                        {
                            TUPLES = true;
                            break;
                        }

                    case "DATA":
                        {
                            DATA = true;
                            break;
                        }

                    case "BOT":
                        {
                            if (TABLE && VECTORS && TUPLES && DATA)
                            {
                                if (rowCount < rows)
                                {
                                    tmpDic.Add(deQuote(items[i + 2]), items[i + 4].Replace("\n", "\r\n"));
                                    rowCount++;
                                    i = i + 4;
                                }
                            }
                            break;
                        }
                    case "EOD":
                        {
                            i = items.Count();
                            break;
                        }
                }
            }

            return tmpDic;
        }


        private void refreshWindow(string inOut)
        {
            this.CodeShower.Text = "";
            foreach (CobRow cr in parentWindow.RowList)
            {
                if (cr.CobLevel < 2)
                {
                    string inFile = parentWindow.CmbLastFile.Text.Substring(parentWindow.CmbLastFile.Text.LastIndexOf("\\") + 1);
                    parentWindow.CreateComment(this.CodeShower, "Moves reference (with loop) " + cr.FieldName, S.ettingUserName, S.ettingCompany, inFile);
                }
                // Header square created

                if (!cr.isAttribute && !cr.SampleStr.Equals(parentWindow.NOMOVE))
                {
                    if (this.CodeShower.Text == "") { }
                    else this.CodeShower.Text += "\r\n";
                    if (inOut == "IN")
                    {
                        if (cr.MoveCode == null)
                        {
                            this.CodeShower.Text += "".PadRight(30) + " " + cr.FieldName.PadRight(30);

                        }
                        else
                        {
                            this.CodeShower.Text += cr.MoveCode.PadRight(30) + " " + cr.FieldName.PadRight(30);
                        }
                    }
                    else
                    {
                        if (cr.MoveFromCode == null)
                        {
                            this.CodeShower.Text += "".PadRight(30) + " " + cr.FieldName.PadRight(30);

                        }
                        else
                        {
                            this.CodeShower.Text += cr.MoveFromCode.PadRight(30) + " " + cr.FieldName.PadRight(30);
                        }
                    }

                }

            }

        }

        private void btnSynchOut_Click(object sender, EventArgs e)
        {
            codeCompleter Cc = new codeCompleter(parentWindow.CmbLastFile.Text, parentWindow.FldPref);
            string fieldCompl = "";
            this.CodeShower.Text = " InPath = " + 
                Cc.PathId + "\r\n InFile = " + 
                Cc.FileId + "\r\n codeFile = " + 
                Cc.CcFileOutId + "\r\n codePath = " + 
                Cc.PathId + 
                Cc.CcFileOutId + "\r\n -------------- \r\n" + this.CodeShower.Text;

            Cc.TryFill_Out_Dic();

            // wrkDic = new Dictionary<string, string>();
            foreach (CobRow cr in parentWindow.RowList)
            {
                if (!cr.isAttribute && !cr.SampleStr.Equals(parentWindow.NOMOVE))
                {
                    if (Cc.WorkDicOut != null && Cc.WorkDicOut.Count > 0)
                    {
                        if (Cc.WorkDicOut.TryGetValue(cr.FieldName, out fieldCompl))
                        {
                            cr.MoveFromCode = fieldCompl;
                        }
                    }
                    if (cr.MoveFromCode == null) { cr.MoveFromCode = " "; }
                    Cc.WorkDicOut[cr.FieldName] = cr.MoveFromCode;
                }
            }

            if (DialogResult.OK == MessageBox.Show("Vill du verkligen spara...?", "Spara kompletterad kod", MessageBoxButtons.OKCancel))
            {
                Cc.Save_Out_Dic();
            }

            refreshWindow("OUT");

            this.CodeShower.Text = " InPath = " + 
                Cc.PathId + "\r\n InFile = " + 
                Cc.FileId + "\r\n codeFile = " + 
                Cc.CcFileOutId + "\r\n codePath = " + 
                Cc.PathId + 
                Cc.CcFileOutId + "\r\n -------------- \r\n" + this.CodeShower.Text;
        }

        private void btnSaveAktualText_Click(object sender, EventArgs e)
        {
            SaveRegCopyFile saveWin = new SaveRegCopyFile();
            saveWin.SavedFile = this.SavedFile;
            saveWin.FileData = this.txtCode.Text;
            saveWin.ShowDialog();
            finalFileSafe = saveWin.finalFileName;
            btnCompare.Enabled = (finalFileSafe.Trim() != "");
        }

        private void ShowCode_Load(object sender, EventArgs e)
        {
            if (parentWindow == null)
            {
                btnSaveAktualText.Enabled = false;
                finalFileSafe = wholeFilePath;
                btnCompare.Enabled = true;
            }
            else
            {
                btnSaveAktualText.Enabled = true;
                btnCompare.Enabled = false;
            }
        }

        private void btnCompare_Click(object sender, EventArgs e)
        {
            existing = "";
            try
            {

                existing = finalFileSafe.Substring(finalFileSafe.LastIndexOf("\\") + 1);
                Process.Start("C:\\Program Files (x86)\\WinMerge\\WinMergeU.exe", finalFileSafe + " Q:\\kII20\\cpy\\" + existing);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Problem vid starta WinMerge :" + ex.Message);
            }
            btnMoveToLib.Enabled = true;
        }

        private void btnMoveToLib_Click(object sender, EventArgs e)
        {
            try
            {
                if (DialogResult.OK == MessageBox.Show("Ok att kopiera :" + finalFileSafe + "\r\ntill Q:\\kII20\\cpy\\" + existing, "Kopiering", MessageBoxButtons.OKCancel))
                {
                    File.Copy(finalFileSafe, "Q:\\kII20\\cpy\\" + existing,true);
                    btnMoveToLib.Enabled = false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Problem vid filkopiering :" + ex.Message);
            }
        }

    }
}
