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.IO;


namespace BulkTap3
{
    public partial class main : Form
    {
        public object lb_item = null;

        /// <summary>
        ///  intionat the froms
        /// </summary>
        Filterbyevent Event_filterfrm = new Filterbyevent();
        FilterIMEI filterfrm = new FilterIMEI();
        FilterIMEI IMEI_filterfrm = new FilterIMEI();
        Filter_Duration Duration_filterfrm = new Filter_Duration();
        FilrerbyDate Date_filterfrm = new FilrerbyDate();
        Find Findfrm = new Find();

        public main()
        {

            InitializeComponent();
          
        }

        private void filenamelist_DragLeave(object sender, EventArgs e)
        {

        }

        private void filenamelist_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                e.Effect = DragDropEffects.All;
            else
                e.Effect = DragDropEffects.None;
        }

        private void main_DragEnter(object sender, DragEventArgs e)
        {
           
        }

        private void main_DragDrop(object sender, DragEventArgs e)
        {
         
        }

        private void filenamelist_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void filenamelist_DragDrop(object sender, DragEventArgs e)
        {
            string[] s = (string[])e.Data.GetData(DataFormats.FileDrop, false);
            int i;
            for (i = 0; i < s.Length; i++)
            {
                filenamelist.Items.Add(s[i], true);
                merge_tree.Nodes.Add(s[i]);
                Split_DGV.Rows.Add(new object[] { false, s[i], "", "" });
            }
        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

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

        private void splitContainer1_Panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void runbtn_Click(object sender, EventArgs e)
        {
            StatusLbl.Text = "Status:Processing..";
            bulkprocessing.RunWorkerAsync();
        }

        private void optionlist_SelectedIndexChanged_1(object sender, EventArgs e)
        {
            findreplacegrp.Visible = false;
            FATgrp.Visible = false;
            Notification_File_grp.Visible = false;
            merge_grp.Visible = false;
            Split_grp.Visible = false;
            Filter_grp.Visible = false;
            foreach (String str in optionlist.SelectedItems )// go through all option
            {
                if (str == "FAT")
                {

                    FATgrp.Visible = true;
                    DateTime LTS;// to get past tow days
                    LTS = DateTime.Now.AddDays(-2);
                    LTStxt.Text = LTS.ToString("yyyyMMddHHmmss"); ;
                }
                if (str == "Find/Replace")
                {
                    findreplacegrp.Visible = true;
                }
                if (str == "Notification File")
                {
                    Notification_File_grp.Visible = true;
                }
                if (str == "Merge")
                {
                    
                    merge_grp.Visible = true;
                }
                if (str == "Split")
                {

                    Split_grp.Visible = true;
                }
                if (str == "Filter")
                {
                    
                    Filter_grp.Visible = true;
                }
            }
            //optionlist.SetItemCheckState(2, CheckState.Indeterminate);
        }

        private void main_Load(object sender, EventArgs e)
        {

        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void toolStripStatusLabel1_Click(object sender, EventArgs e)
        {

        }

        private void Notificaton_file_op1_CheckedChanged(object sender, EventArgs e)
        {
            Note_pnl.Enabled = false;
        }

        private void Notificaton_file_op2_CheckedChanged(object sender, EventArgs e)
        {
            Note_pnl.Enabled = true;
        }

        private void Note_create_btn_Click(object sender, EventArgs e)
        {
            fldbd.ShowDialog();
            string filename;
            int seq_from,seq_to;
            if (Note_Type_op1.Checked == true)
                filename = "CD";
            else
                filename = "TD";
            filename += Note_sender_txt.Text;
            filename += Note_recip_txt.Text;
            if (!int.TryParse(Note_seq_from_txt.Text,out seq_from))
                MessageBox.Show("Error in Sequance");
            if (!int.TryParse(Note_seq_to_txt.Text,out seq_to))
                MessageBox.Show("Error in Sequance");
           
            DateTime LTS;// to get past tow days
            LTS = DateTime.Now.AddDays(-2);
            TotalProcessBar.Maximum = seq_to - seq_from +1;
            TotalProcessBar.Value = 0;
            for (int count=seq_from; count<=seq_to;count++)
            {
                ProcessBar.Value = 0;
                string seq = String.Format("{0:D5}", count);
                functions.Create_Notifications(fldbd.SelectedPath+"\\" + filename + seq, Note_sender_txt.Text, Note_recip_txt.Text, seq, LTS.ToString("yyyyMMddHHmmss"), Note_ver_txt1.Text, Note_ver_txt2.Text);
                ProcessBar.Value = 100;
                TotalProcessBar.Value += 1;
            }
            ProcessBar.Value = 0;
            MessageBox.Show("Done!");
        }

        private void merge_tree_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                e.Effect = DragDropEffects.All;
            else
                e.Effect = DragDropEffects.None;


        }

        private void merge_tree_DragDrop(object sender, DragEventArgs e)
        {
            string[] s = (string[])e.Data.GetData(DataFormats.FileDrop, false);
            int i;
            // dropnode=treeView2.GetNodeAt(e.X, e.Y);
            Point pt = new Point(e.X, e.Y);

            // Convert to a point in the TreeView's coordinate system.
            pt = merge_tree.PointToClient(pt);
            merge_tree.SelectedNode = merge_tree.GetNodeAt(pt);
            if (merge_tree.SelectedNode != null)
            {
                for (i = 0; i < s.Length; i++)
                    merge_tree.SelectedNode.Nodes.Add(s[i]).Checked = true;
                merge_tree.SelectedNode.Checked = true;
            }
            //treeView2.Nodes.Add( dropnode  );
        }

        private void merge_clear_btn_Click(object sender, EventArgs e)
        {
            merge_tree.Nodes.Clear();
            if (filenamelist.Items.Count > 0)
            {
                for (int counter = 0; counter < filenamelist.Items.Count; counter++)
                {
                    merge_tree.Nodes.Add(filenamelist.Items[counter].ToString());
                }
            }
        }

        private void Filelist_clear_btn_Click(object sender, EventArgs e)
        {
            filenamelist.Items.Clear();
            merge_tree.Nodes.Clear();
            Split_DGV.Rows.Clear();
        }

        private void Filelist_selection_btn_Click(object sender, EventArgs e)
        {
            if (Filelist_selection_btn.Text == "Uncheck all")
            {

                foreach (int i in filenamelist.CheckedIndices)
                {
                    filenamelist.SetItemCheckState(i, CheckState.Unchecked);
                }
                Filelist_selection_btn.Text = "Check all";
            }
            else if (Filelist_selection_btn.Text == "Check all")
            {
                for (int i = 0; i < filenamelist.Items.Count; i++)
                {
                    filenamelist.SetItemChecked(i, true);
                }
                Filelist_selection_btn.Text = "Uncheck all";
            }
        }

        private void Split_rb1_CheckedChanged(object sender, EventArgs e)
        {
            if (Split_rb1.Checked)
            {
                Split_DGV.Columns[2].HeaderText = "Parts";
                ((DataGridViewTextBoxColumn)Split_DGV.Columns[2]).MaxInputLength = 32767;

            }
            else
            {
                Split_DGV.Columns[2].HeaderText = "Timestamp";
                ((DataGridViewTextBoxColumn)Split_DGV.Columns[2]).MaxInputLength = 14;
            }
        }

        private void checkBox8_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StatusLbl.Text = "Status:Open";

            if (OFD.ShowDialog() != DialogResult.Cancel)
            {
                if (OFD.FileName != "")
                {
                    ChangesList.Clear();
                    M_branch_tree.Nodes.Clear();
                    B_tree.Nodes.Clear();
                    Opend_Filename = OFD.FileName;
                    string filename = Path.GetFileName(Opend_Filename);
                    this.Text = "Geo - " + filename;
                    backgroundWorker1.RunWorkerAsync();
                }
            }
            //TreeNode t=new TreeNode();
            //System.Threading.Thread newThread = new System.Threading.Thread(() => { t = functions.OpenFile_tree(OFD.FileName, M_branch_tree); });
            //newThread.Start();

            //newThread.Join();
            //while (!newThread.IsAlive) ;
            //M_branch_tree.Nodes.Add(t);
            //MessageBox.Show(t);
            //t=functions.OpenFile_tree(OFD.FileName, M_branch_tree);
            
            

        }

        private void fileToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }
        public string To_var_length;
        public string Opend_Filename;
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {

                StatusLbl.Text = "Status:Processing...";
                TreeNode t = new TreeNode();
                backgroundWorker1.ReportProgress(1);
                To_var_length = functions.To_variable_lenth(Opend_Filename, Opend_Filename + ".tmp");
                if (To_var_length == "done")
                {
                    t = functions.OpenFile_tree(Opend_Filename + ".tmp", M_branch_tree, backgroundWorker1);
                    Opend_Filename += ".tmp";
                }
                else if (To_var_length == "no change")
                    t = functions.OpenFile_tree(Opend_Filename, M_branch_tree, backgroundWorker1);
                else
                    MessageBox.Show("File is corrupted!");


                e.Result = t;
            
          
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            StatusLbl.Text = "Status:Done";
            TreeNode j = e.Result as TreeNode;
            TotalProcessBar.Value = 0;
            //MessageBox.Show(j.Nodes[0].Text);
            M_branch_tree.Nodes.Add(j);

            for (int count = 1; count < toolStrip1.Items.Count;count++ )
                toolStrip1.Items[count].Enabled = true;
            editToolStripMenuItem.Enabled = true;
                
            //MessageBox.Show(M_branch_tree.Nodes[0].Nodes[0].Tag.ToString());
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            
            TotalProcessBar.Value = e.ProgressPercentage;
        }

        private void M_branch_tree_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (M_branch_tree.SelectedNode.Tag != null)
            {
                B_tree.Nodes.Clear();
                int End_of_Identifier;
                string TagStr = M_branch_tree.SelectedNode.Tag.ToString();
                if (TagStr.IndexOf(',') == -1)
                {
                    End_of_Identifier = functions.Open_identifier_tree(Opend_Filename, Convert.ToInt32(M_branch_tree.SelectedNode.Tag), B_tree);
                    M_branch_tree.SelectedNode.Tag += "," + End_of_Identifier.ToString();
                }
                else
                {
                    string[] str = M_branch_tree.SelectedNode.Tag.ToString().Split(',');
                    End_of_Identifier = functions.Open_identifier_tree(Opend_Filename, Convert.ToInt32(str[0]), B_tree);
                }
                functions.Update_Changes_on_tree(B_tree.TopNode, ChangesList);
                B_tree.ExpandAll();
                B_tree.SelectedNode = B_tree.Nodes[0];
            }
        }

        private void bulkprocessing_DoWork(object sender, DoWorkEventArgs e)
        {
            double precentage;
            Boolean FR_change = false;//find and replace
            Boolean Fat_change = false;
            Boolean Merge_change = false;
            Boolean Bearked = false;
            string ok_To_var_length = ""; // change are made correctly

            double count = filenamelist.CheckedItems.Count; //for process bar calculations
            double current = 0; //for process bar calculations
            
            foreach (String file in filenamelist.CheckedItems)// go through all files
            {
                string filename = Path.GetFileName(file);
                string lastFolder = Path.GetDirectoryName(file);
                foreach (String str in optionlist.CheckedItems)// go through all option
                {
                    if (str == "FAT")
                    {
                        if (LTStxt.Text == "" || LTStxt.Text.Length != 14)
                        {
                            MessageBox.Show("Erorr in entering FAT");
                            return;
                        }
                        bulkprocessing.ReportProgress(10, "process");
                        Boolean ok_FAT;
                        if (!Directory.Exists(lastFolder + "\\Result"))
                            Directory.CreateDirectory(lastFolder + "\\Result");
                        ok_FAT = functions.FAT(file, LTStxt.Text, lastFolder + "\\Result\\" + filename);
                        Fat_change = true;
                        bulkprocessing.ReportProgress(100, "process");
                    }
                    if (str == "Find/Replace")
                    {
                        if (child_Iden_cb_index==-1)
                        {
                            MessageBox.Show("Please Select Field");
                            return;
                        }
                        if (find_txt.Text =="")
                        {
                            MessageBox.Show("Please enter value for Search");
                            return;
                        }
                        if (replace_txt.Text == "")
                        {
                            MessageBox.Show("Please enter value for replace");
                            return;
                        }
                        bulkprocessing.ReportProgress(10, "process");
                        if (!Directory.Exists(lastFolder + "\\Result"))
                            Directory.CreateDirectory(lastFolder + "\\Result");

                        if (!Fat_change)
                        {
                            ok_To_var_length = functions.To_variable_lenth(file, lastFolder + "\\Result\\" + filename);
                        }
                        else
                        {
                            ok_To_var_length = functions.To_variable_lenth(lastFolder + "\\Result\\" + filename, lastFolder + "\\Result\\" + filename);
                        }
                        string time;

                        if (ok_To_var_length == "done" )

                            time = functions.Find_and_replace(child_Iden_cb_index, find_txt.Text, replace_txt.Text, lastFolder + "\\Result\\" + filename, lastFolder + "\\Result\\" + filename);
                        else if (ok_To_var_length == "no change")
                            time = functions.Find_and_replace(child_Iden_cb_index, find_txt.Text, replace_txt.Text, file, lastFolder + "\\Result\\" + filename);
                        else
                        {
                            MessageBox.Show("File is corrupted!");
                            Bearked=true;
                            break;
                        }
                            FR_change = true;

                        //     if (!Directory.Exists(lastFolder + "\\Result"))
                        //         Directory.CreateDirectory(lastFolder + "\\Result");
                        //     time = functions.Find_and_replace(child_Iden_cb.SelectedIndex, find_txt.Text, replace_txt.Text, file, lastFolder + "\\Result\\" + filename);
                        //     many_change = true;
                        bulkprocessing.ReportProgress(100, "process");

                    }
                    if (str == "Notification File" && Notificaton_file_op1.Checked == true)
                    {
                        bulkprocessing.ReportProgress(10, "process");
                        if (!Directory.Exists(lastFolder + "\\Result"))
                            Directory.CreateDirectory(lastFolder + "\\Result");
                        functions.Create_Notifications_from_file(file, lastFolder + "\\Result\\" + filename);
                        bulkprocessing.ReportProgress(100, "process");
                    }
                    if (str == "Merge")
                    {
                        bool first_file = true;
                        bulkprocessing.ReportProgress(10, "process");
                        if (!Directory.Exists(lastFolder + "\\Result"))
                            Directory.CreateDirectory(lastFolder + "\\Result");
                        TreeNodeCollection nodes = merge_tree.Nodes;
                        foreach (TreeNode parent in nodes)
                        {
                            if (parent.Parent == null)
                            {
                                //MessageBox.Show(n.Text);
                                if (parent.Checked == true)
                                {
                                    foreach (TreeNode child in parent.Nodes)
                                    {
                                        if (child.Checked == true)
                                        {
                                            string merge_filename = Path.GetFileName(parent.Text);
                                            if ((!FR_change && first_file) && (!Fat_change && first_file))
                                            {
                                                ok_To_var_length = functions.To_variable_lenth(parent.Text, lastFolder + "\\Result\\" + merge_filename);
                                            }
                                            else
                                            {
                                                if (Fat_change && first_file)
                                                    ok_To_var_length = functions.To_variable_lenth(lastFolder + "\\Result\\" + merge_filename, lastFolder + "\\Result\\" + merge_filename);
                                            }
                                            //MessageBox.Show(k.Text);
                                            if (ok_To_var_length=="done")
                                                functions.Merge_file(lastFolder + "\\Result\\" + merge_filename, child.Text, lastFolder + "\\Result\\" + merge_filename);
                                            else if (To_var_length == "no change")
                                                if (first_file)
                                                {
                                                    functions.Merge_file(parent.Text, child.Text, lastFolder + "\\Result\\" + merge_filename);
                                                    first_file = false;
                                                }
                                                else
                                                    functions.Merge_file(lastFolder + "\\Result\\" + merge_filename, child.Text, lastFolder + "\\Result\\" + merge_filename);
                                            else
                                            {
                                                MessageBox.Show("File is corrupted!");
                                                Bearked = true;
                                                break;
                                            }
                                                
                                        }
                                    }
                                }
                            }
                        }
                        bulkprocessing.ReportProgress(100, "process");
                    }
                    if (str == "Split")
                    {
                        bulkprocessing.ReportProgress(10, "process");
                        if (!Directory.Exists(lastFolder + "\\Result"))
                            Directory.CreateDirectory(lastFolder + "\\Result");
                        foreach (DataGridViewRow row in Split_DGV.Rows)
                        {
                            if (!row.IsNewRow)
                            {
                                if (row.Cells[0].GetType() == typeof(DataGridViewCheckBoxCell))
                                {
                                    if (Convert.ToString(row.Cells[0].Value).Contains("True"))
                                    {
                                        if (row.Cells[3].Value == null || row.Cells[2].Value == null)
                                        {
                                            MessageBox.Show("Field is Missing");
                                            return;
                                        }
                                        if (!FR_change && !Fat_change)
                                        {
                                            ok_To_var_length = functions.To_variable_lenth(file, lastFolder + "\\Result\\" + filename);
                                        }
                                        else
                                        {
                                            if (Fat_change)
                                                ok_To_var_length = functions.To_variable_lenth(lastFolder + "\\Result\\" + filename, lastFolder + "\\Result\\" + filename);
                                        }
                                        string splitfilename = Path.GetFileName(row.Cells[1].Value.ToString());
                                            //ok_To_var_length = functions.To_variable_lenth(row.Cells[1].Value.ToString(), lastFolder + "\\Result\\" + splitfilename);

                                        if (Split_rb1.Checked)
                                        {
                                            if (ok_To_var_length == "done")
                                                functions.Split_file(lastFolder + "\\Result\\" + splitfilename, lastFolder + "\\Result", row.Cells[3].Value.ToString(), int.Parse(row.Cells[2].Value.ToString()));
                                            else if (To_var_length == "no change")
                                                functions.Split_file(row.Cells[1].Value.ToString(), lastFolder + "\\Result", row.Cells[3].Value.ToString(), int.Parse(row.Cells[2].Value.ToString()));
                                            else
                                            {
                                                MessageBox.Show("File is corrupted!");
                                                Bearked = true;
                                                break;
                                            }
                                                
                                        }
                                        else
                                        {
                                            byte[] date = Encoding.ASCII.GetBytes(row.Cells[2].Value.ToString());
                                            if (ok_To_var_length == "done")
                                                functions.Split_file_Date(lastFolder + "\\Result\\" + splitfilename, lastFolder + "\\Result", row.Cells[3].Value.ToString(), date);
                                            else if (To_var_length == "no change")
                                                functions.Split_file_Date(row.Cells[1].Value.ToString(), lastFolder + "\\Result", row.Cells[3].Value.ToString(), date);
                                            else
                                            {
                                                MessageBox.Show("File is corrupted!");
                                                Bearked = true;
                                                break;
                                            }
                                                
                                        }
                                    }
                                }
                            }
                        }
                        bulkprocessing.ReportProgress(100, "process");
                    }
                    if (str == "Filter")
                    {
                        bulkprocessing.ReportProgress(10, "process");
                        if (!Directory.Exists(lastFolder + "\\Result"))
                            Directory.CreateDirectory(lastFolder + "\\Result");

                        if (!FR_change && !Fat_change)
                        {
                            ok_To_var_length = functions.To_variable_lenth(file, lastFolder + "\\Result\\" + filename);
                        }
                        else
                        {
                            if (Fat_change)
                                ok_To_var_length = functions.To_variable_lenth(lastFolder + "\\Result\\" + filename, lastFolder + "\\Result\\" + filename);
                        }


                       
                            bool[] call_event_type = new bool[9];
                            call_event_type[0] = Filter_cb1.Checked;//MobileOriginatedCall
                            call_event_type[1] = Filter_cb2.Checked;//MobileTerminatedCall
                            call_event_type[2] = Filter_cb3.Checked;//SupplServiceEvent
                            call_event_type[3] = Filter_cb4.Checked;//ServiceCentreUsage
                            call_event_type[4] = Filter_cb5.Checked;//GprsCall
                            call_event_type[5] = Filter_cb6.Checked;//ContentTransaction
                            call_event_type[6] = Filter_cb7.Checked;//LocationService
                            call_event_type[7] = Filter_cb8.Checked;//MessagingEvent
                            call_event_type[8] = Filter_cb9.Checked;//MobileSession
                            if (ok_To_var_length == "done" || !FR_change)
                               functions.Filter_Records(lastFolder + "\\Result\\" + filename, lastFolder + "\\Result\\" + filename, call_event_type);
                            else if (ok_To_var_length == "no change")
                                if (Fat_change)
                                    functions.Filter_Records(lastFolder + "\\Result\\" + filename, lastFolder + "\\Result\\" + filename, call_event_type);
                                else
                                    functions.Filter_Records(file, lastFolder + "\\Result\\" + filename, call_event_type);
                            else
                            {
                                MessageBox.Show("File is corrupted!");
                                Bearked = true;
                                break;
                            }
                        // many_change = true;

                        //     if (!Directory.Exists(lastFolder + "\\Result"))
                        //         Directory.CreateDirectory(lastFolder + "\\Result");
                        //     time = functions.Find_and_replace(child_Iden_cb.SelectedIndex, find_txt.Text, replace_txt.Text, file, lastFolder + "\\Result\\" + filename);
                        //     many_change = true;
                        bulkprocessing.ReportProgress(100, "process");
                    }

                }

                current++;
                precentage = (current / count) * 100;
                bulkprocessing.ReportProgress((int)precentage, "totalprocess");
                if (Bearked)
                {
                    Bearked = false;
                    continue;
                }
            }
            
        }

        private void bulkprocessing_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            StatusLbl.Text = "Status:Done";
            TotalProcessBar.Value = 0;
            ProcessBar.Value = 0;
        }

        private void bulkprocessing_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
           
            String str = e.UserState as String;
           int process = e.ProgressPercentage ;
            if (str == "process")
               ProcessBar.Value = process;
            else
                TotalProcessBar.Value = process;
            
        }
        public int child_Iden_cb_index=-1;
        private void child_Iden_cb_SelectedIndexChanged(object sender, EventArgs e)
        {
            child_Iden_cb_index = child_Iden_cb.SelectedIndex;
        }

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

        private void Notificaton_file_op3_Click(object sender, EventArgs e)
        {
            fldbd.ShowDialog();
            OFD.ShowDialog();

            if (File.Exists(Opend_Filename))
            {
                using (StreamReader sr = File.OpenText(Opend_Filename))
                {
                    string line = "";
                    string TC = "";
                    string Sender = "";
                    string Recipiant = "";
                    string Seq = "";
                    string ver = "";
                    string res = "";
                    //TotalProcessBar.Maximum = sr.
                    while ((line = sr.ReadLine()) != null)
                    {

                        string[] split = line.Split(',');
                        if (split[0].Length == 17)
                        {
                            TC = split[0].Substring(0, 2);
                            Sender = split[0].Substring(2, 5);
                            Recipiant = split[0].Substring(7, 5);
                            Seq = split[0].Substring(12, 5);
                        }
                        if (split[1].Length == 1)
                        {
                            ver = split[1];
                        }
                        if (split[2].Length >= 1)
                        {
                            res = split[2];
                        }
                        DateTime LTS;// to get past tow days
                        LTS = DateTime.Now.AddDays(-2);
                        functions.Create_Notifications(fldbd.SelectedPath + "\\" + split[0], Sender, Recipiant, Seq, LTS.ToString("yyyyMMddHHmmss"), ver, res);
                        //TotalProcessBar.Value += 1;
                    }
                }
            }


            MessageBox.Show("Done!");
        }

        private void TSGotoBtn_Click(object sender, EventArgs e)
        {
           // string str= In ("Do you need to update the values?", "Max Value", string.Empty, -1, -1);

            Goto Gotofrm = new Goto();
            Gotofrm.Set_tree(M_branch_tree);
            Gotofrm.Show();
            
        }
        TreeNode mySelectedNode;
        private void B_tree_MouseDown(object sender, MouseEventArgs e)
        {
           
        }

        private void B_tree_MouseDoubleClick_1(object sender, MouseEventArgs e)
        {
            if (mySelectedNode != null && mySelectedNode.Parent != null && mySelectedNode.Nodes.Count == 0 && mySelectedNode.ImageIndex!=0)
            {
                B_tree.SelectedNode = mySelectedNode;
                //Treeview1.LabelEdit = true;
                if (!mySelectedNode.IsEditing)
                {
                    // mySelectedNode.BeginEdit();
                    Point pt = new Point(e.X, e.Y);

                    // Convert to a point in the TreeView's coordinate system.
                    pt = B_tree.PointToClient(pt);
                    //textBox5.Top = Treeview1.Top + pt.Y;
                    //textBox5.Left = Treeview1.Left + pt.X;
                    //B_tree.SelectedNode = B_tree.GetNodeAt(pt);
                    string[] nodename = B_tree.SelectedNode.Text.Split(':');

                    var font = new Font(B_tree.Font.Name, B_tree.Font.Size, B_tree.Font.Style);
                    // x=TextRenderer.MeasureText(mySelectedNode.Text, font);
                    Edittxt.SetBounds(B_tree.Left + B_tree.SelectedNode.Bounds.X + TextRenderer.MeasureText(nodename[0]+"        ", font).Width,
        B_tree.Top + B_tree.SelectedNode.Bounds.Y, TextRenderer.MeasureText(nodename[1].TrimStart(), font).Width+20, Edittxt.Height);

                    Edittxt.Text = nodename[1].TrimStart();
                    Edittxt.Visible = true;
                    Edittxt.Focus();
                }
            }
          /*  else
            {
                MessageBox.Show("No tree node selected or selected node is a root node.\n" +
                   "Editing of root nodes is not allowed.", "Invalid selection");
            }*/
        }
        List<functions.Changes> ChangesList = new List<functions.Changes>();
        bool Text_edit_change = false;
        private void Edittxt_Leave(object sender, EventArgs e)
        {
            Edittxt.Visible = false;
            Text_edit_change = false;
        }
        
        private void Edittxt_TextChanged(object sender, EventArgs e)
        {
            Text_edit_change = true;

        }

        private void TSSaveBtn_Click(object sender, EventArgs e)
        {
           
           // SFD.ShowDialog();
            if (Opend_Filename!= "")
            {

                functions.Save_identifier_tree(Opend_Filename, ChangesList, OFD.FileName);
                
            }
        }

        private void SFD_FileOk(object sender, CancelEventArgs e)
        {

        }

        private void Edittxt_KeyDown(object sender, KeyEventArgs e)
        {

            if (e.KeyCode == Keys.Enter)
            {
                if (Text_edit_change == true && B_tree.SelectedNode != null)
                {
                    string[] nodename = B_tree.SelectedNode.Text.Split(':');
                    B_tree.SelectedNode.Text = nodename[0] + ":        " + Edittxt.Text;
                    functions.Changes New_Edit;
                    string Node_tag = B_tree.SelectedNode.Tag.ToString();
                    string[] str = Node_tag.Split(',');
                    New_Edit.identifer = int.Parse(str[0]);
                    New_Edit.identifer_start = int.Parse(str[1]);
                    New_Edit.identifer_end = int.Parse(str[2]);
                    New_Edit.type = 0;
                    New_Edit.Parent = false;
                    New_Edit.Node_index = B_tree.SelectedNode.Index;
                    New_Edit.Parent_Name = int.Parse(B_tree.SelectedNode.Parent.Tag.ToString().Split(',')[0]);
                    New_Edit.New_Value = Edittxt.Text;
                    //if (New_Edit.identifer_end != 0)
                    //{
                        if (Edittxt.Text != nodename[1].TrimStart())
                            ChangesList.Add(New_Edit);
                    //}
                    //else
                    //{
                       //int Found_index= Insert_List.FindIndex(x => x.identifer_start == New_Edit.identifer_start && x.identifer == New_Edit.identifer && x.Node_index == B_tree.SelectedNode.Index );
                        //if (Found_index >0)
                        //{
                            //Insert_List[Found_index].New_Value = Edittxt.Text;
                           
                        //}
                    //}
                    Text_edit_change = false;
                    Edittxt.Visible = false;
                    B_tree.Focus();
                }
            }
            if (e.KeyCode == Keys.Escape)
            {
                Edittxt.Text = "";
                Edittxt.Visible = false;
                Text_edit_change = false;
                B_tree.Focus();
            }
        }

        private void B_tree_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == (Keys.Control | Keys.C))
            {
                if (B_tree.SelectedNode != null)
                {
                    Clipboard.SetText(B_tree.SelectedNode.Text + "\r\n" + functions.tree_to_text(B_tree.SelectedNode, B_tree.SelectedNode.Level));
                }
                e.SuppressKeyPress = true;
            }
            if (e.KeyData == (Keys.Control | Keys.V))
            {
                int linenumber = 1; //should start with one because of the first line [0] is not counted
                string clipb = Clipboard.GetText();
                if (B_tree.SelectedNode != null)
                    functions.Paste(B_tree.SelectedNode, B_tree.SelectedNode, clipb, ref linenumber, ChangesList);
            }
            if (e.KeyData == Keys.Enter)
            {
                if (B_tree.SelectedNode != null && B_tree.SelectedNode.Parent != null && B_tree.SelectedNode.Nodes.Count == 0 && B_tree.SelectedNode.ImageIndex != 0)
                {
                   
                    

                        // Convert to a point in the TreeView's coordinate system.
                       
                        //textBox5.Top = Treeview1.Top + pt.Y;
                        //textBox5.Left = Treeview1.Left + pt.X;
                        //B_tree.SelectedNode = B_tree.
                        string[] nodename = B_tree.SelectedNode.Text.Split(':');

                        var font = new Font(B_tree.Font.Name, B_tree.Font.Size, B_tree.Font.Style);
                        // x=TextRenderer.MeasureText(mySelectedNode.Text, font);
                        Edittxt.SetBounds(B_tree.Left + B_tree.SelectedNode.Bounds.X + TextRenderer.MeasureText(nodename[0] + "        ", font).Width,
            B_tree.Top + B_tree.SelectedNode.Bounds.Y, TextRenderer.MeasureText(nodename[1].TrimStart(), font).Width + 20, Edittxt.Height);

                        Edittxt.Text = nodename[1].TrimStart();
                        Edittxt.Visible = true;
                        Edittxt.Focus();
                    
                }
            }
        }

        private void M_branch_tree_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            if (e.Node.ImageIndex == 0)
            {
                e.Node.ImageIndex = 1;
                e.Node.SelectedImageIndex = 1;
            }
        }

        private void M_branch_tree_BeforeCollapse(object sender, TreeViewCancelEventArgs e)
        {
            if (e.Node.ImageIndex == 1)
            {
                e.Node.ImageIndex = 0;
                e.Node.SelectedImageIndex = 0;
            }
        }

        private void B_tree_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            if (e.Node.ImageIndex == 0)
            {
                e.Node.ImageIndex = 1;
                e.Node.SelectedImageIndex = 1;
            }
        }

        private void B_tree_BeforeCollapse(object sender, TreeViewCancelEventArgs e)
        {
            if (e.Node.ImageIndex == 1)
            {
                e.Node.ImageIndex = 0;
                e.Node.SelectedImageIndex = 0;
            }
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            if (B_tree.SelectedNode!=null)
            Clipboard.SetText(B_tree.SelectedNode.Text + "\r\n" + functions.tree_to_text(B_tree.SelectedNode, B_tree.SelectedNode.Level));
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            int linenumber = 1; //should start with one because of the first line [0] is not counted
            string clipb = Clipboard.GetText();
            if (B_tree.SelectedNode != null)
                functions.Paste(B_tree.SelectedNode, B_tree.SelectedNode, clipb, ref linenumber, ChangesList);
        }

        //List<functions.Deleted_iden> DeletedList = new List<functions.Deleted_iden>();
        private void TSDelete_Click(object sender, EventArgs e)
        {
            functions.Changes Deleted_Item = new functions.Changes();
            if (M_branch_tree.Focused && M_branch_tree.SelectedNode != null)
            {
                if (M_branch_tree.SelectedNode.Tag != null)
                {
                    string[] str = M_branch_tree.SelectedNode.Tag.ToString().Split(','); ;
                    Deleted_Item.identifer = 0;
                    Deleted_Item.identifer_start = int.Parse(str[0]);
                    Deleted_Item.identifer_end = int.Parse(str[1]);
                    Deleted_Item.Parent = true;
                    Deleted_Item.type = 1;
                    Deleted_Item.Node_index = M_branch_tree.SelectedNode.Index;
                    if (M_branch_tree.SelectedNode.Parent.Tag != null)
                        Deleted_Item.Parent_Name = int.Parse(M_branch_tree.SelectedNode.Parent.Tag.ToString().Split(',')[0]);
                    else
                        Deleted_Item.Parent_Name = 1;    
                    ChangesList.Add(Deleted_Item);
                    M_branch_tree.SelectedNode.Remove();
                }

            }
            if (B_tree.Focused && B_tree.SelectedNode != null)
            {
                if (B_tree.SelectedNode.Tag != null)
                {
                    string[] str = B_tree.SelectedNode.Tag.ToString().Split(','); ;
                    Deleted_Item.identifer = int.Parse(str[0]);
                    Deleted_Item.identifer_start = int.Parse(str[1]);
                    Deleted_Item.identifer_end = int.Parse(str[2]);
                    Deleted_Item.Node_index = B_tree.SelectedNode.Index;
                    Deleted_Item.type = 1;
                    Deleted_Item.Parent=(B_tree.SelectedNode.GetNodeCount(false) > 0) ? true : false;
                    Deleted_Item.Parent_Name = int.Parse(B_tree.SelectedNode.Parent.Tag.ToString().Split(',')[0]); 

                    ChangesList.Add(Deleted_Item);
                    if (B_tree.SelectedNode.Parent!=null)
                        B_tree.SelectedNode.Remove();
                    else
                    {
                        B_tree.SelectedNode.Remove();
                        M_branch_tree.SelectedNode.Remove();
                    }
                }
            }
        }
        //List<functions.inserted_iden> Insert_List = new List<functions.inserted_iden>();
        private void TSInsert_Click(object sender, EventArgs e)
        {
            InsertFrm insertfrm= new InsertFrm();
            if (B_tree.Focused && B_tree.SelectedNode != null)
            {
                insertfrm.get_missing_identifier(B_tree.SelectedNode, B_tree, ChangesList, Opend_Filename);
                insertfrm.Show();
            }
           
        }
        public void Insert_missing_identifer(int index,string identifier_name)
        {
            B_tree.Nodes.Insert(index, identifier_name);
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            if (ChangesList.Count > 0)
            {
                ChangesList.RemoveAt(ChangesList.Count - 1);
                if (M_branch_tree.SelectedNode.Tag != null)
                {
                    B_tree.Nodes.Clear();
                    int End_of_Identifier;
                    string TagStr = M_branch_tree.SelectedNode.Tag.ToString();
                    if (TagStr.IndexOf(',') == -1)
                    {
                        End_of_Identifier = functions.Open_identifier_tree(Opend_Filename, Convert.ToInt32(M_branch_tree.SelectedNode.Tag), B_tree);
                        M_branch_tree.SelectedNode.Tag += "," + End_of_Identifier.ToString();
                    }
                    else
                    {
                        string[] str = M_branch_tree.SelectedNode.Tag.ToString().Split(',');
                        End_of_Identifier = functions.Open_identifier_tree(Opend_Filename, Convert.ToInt32(str[0]), B_tree);
                    }
                    functions.Update_Changes_on_tree(B_tree.TopNode, ChangesList);
                    B_tree.ExpandAll();
                    B_tree.SelectedNode = B_tree.Nodes[0];
                }
            }
        }
        TreeNode clonedNode;
        bool Filtered = false;

        private void TSFilterByEvent_Click(object sender, EventArgs e)
        {
            //FilterTree.Nodes.Clear();
            B_tree.Nodes.Clear();
            if (!Filtered)
            {
                clonedNode = (TreeNode)M_branch_tree.Nodes[0].Clone();
            }
     /*       else
            {
                M_branch_tree.Nodes.Clear();
                M_branch_tree.Nodes.Add(clonedNode);
            }*/
            Filtered = true;
            //FilterTree.Nodes.Add(clonedNode);
                        /*indlenV == 9  ||
                        indlenV == 10 ||
                        indlenV == 11 ||
                        indlenV == 12 ||
                        indlenV == 14 ||
                        indlenV == 17 ||
                        indlenV == 297||
                        indlenV == 433||
                        indlenV == 434*/
            
            
            M_branch_tree.Nodes[0].Expand();

            Event_filterfrm.TreeNode(M_branch_tree, clonedNode);
            Event_filterfrm.Show();

                
        }

        private void toolStripButton1_Click_1(object sender, EventArgs e)
        {
           // TreeNode[] filtered_node = functions.Filter_by_identifier(M_branch_tree.Nodes[0].Nodes[3], 129, "424030102992349", Opend_Filename);
           // TreeNode[] filtered_node = functions.Filter_Greater_Less_duration(M_branch_tree.Nodes[0].Nodes[3], 223, ">27", Opend_Filename);
           // TreeNode[] filtered_node = functions.Filter_Greater_Less_timeStamp(M_branch_tree.Nodes[0].Nodes[3], 16, "20140321122546", Opend_Filename,1);
           // TreeNode[] filtered_node = functions.Filter_Between_timeStamp(M_branch_tree.Nodes[0].Nodes[3], 16, "20140320060856", "20140320093418", Opend_Filename);
           //if (filtered_node.Length>=0)
           //{
           //    M_branch_tree.Nodes[0].Nodes[3].Nodes.Clear();
           //    M_branch_tree.Nodes[0].Nodes[3].Nodes.AddRange(filtered_node);
           //}
            // for (int count = 0; count < filtered_node.Length; count++)
           // {
           //     M_branch_tree.Nodes.Remove(filtered_node[count]);
           // }
            B_tree.Nodes.Clear();
            if (!Filtered)
            {
                clonedNode = (TreeNode)M_branch_tree.Nodes[0].Clone();
            }
          /*  else
            {
                M_branch_tree.Nodes.Clear();
                M_branch_tree.Nodes.Add(clonedNode);
            }*/
            Filtered = true;

            

            M_branch_tree.Nodes[0].Expand();

            IMEI_filterfrm.TreeNode(M_branch_tree, Opend_Filename, ChangesList);
            IMEI_filterfrm.Show();
        }

        private void TSFilterDuration_Click(object sender, EventArgs e)
        {
            B_tree.Nodes.Clear();
            if (!Filtered)
            {
                clonedNode = (TreeNode)M_branch_tree.Nodes[0].Clone();
            }
          /*  else
            {
                M_branch_tree.Nodes.Clear();
                M_branch_tree.Nodes.Add(clonedNode);
            }*/
            Filtered = true;

            

            M_branch_tree.Nodes[0].Expand();

            Duration_filterfrm.TreeNode(M_branch_tree, Opend_Filename, ChangesList);
            Duration_filterfrm.Show();
        }

        private void TSFilterDate_Click(object sender, EventArgs e)
        {
            B_tree.Nodes.Clear();
            if (!Filtered)
            {
                clonedNode = (TreeNode)M_branch_tree.Nodes[0].Clone();
            }
       /*     else
            {
                M_branch_tree.Nodes.Clear();
                M_branch_tree.Nodes.Add(clonedNode);
            }*/
            Filtered = true;

            

            M_branch_tree.Nodes[0].Expand();

            Date_filterfrm.TreeNode(M_branch_tree, Opend_Filename);
            Date_filterfrm.Show();
        }

        private void toolStripButton1_Click_2(object sender, EventArgs e)
        {

            if (Findfrm == null)
            {
                Findfrm = new Find();
            }

            M_branch_tree.Nodes[0].Expand();

            Findfrm.TreeNode(M_branch_tree,B_tree, Opend_Filename, ChangesList);
            Findfrm.Show();
        }
        


        private void TSFilterDisable_Click(object sender, EventArgs e)
        {
            if (clonedNode != null)
            {
                Filtered = false;
                M_branch_tree.Nodes.Clear();
                M_branch_tree.Nodes.Add(clonedNode);
            }
        }

        private void closeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ChangesList.Clear();
            M_branch_tree.Nodes.Clear();
            B_tree.Nodes.Clear();
            if( backgroundWorker1.IsBusy)
                backgroundWorker1.CancelAsync();
            for (int count = 1; count < toolStrip1.Items.Count; count++)
                toolStrip1.Items[count].Enabled = false;
            editToolStripMenuItem.Enabled = false;
        }

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

        private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {

            if (SFD.ShowDialog() != DialogResult.Cancel)
            {
                if (SFD.FileName != "")
                {

                    functions.Save_identifier_tree(Opend_Filename, ChangesList, SFD.FileName);

                }
            }
        }

        private void multiOpenToolStripMenuItem_Click(object sender, EventArgs e)
        {
            fldbd.ShowDialog();
            if (fldbd.SelectedPath != "")
            {
                string[] filePaths = Directory.GetFiles(fldbd.SelectedPath, "CD*",
                    SearchOption.AllDirectories);
                filenamelist.Items.AddRange(filePaths);
            }
        }

        private void toolsBarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            toolStrip1.Visible = !toolsBarToolStripMenuItem.Checked;
            toolsBarToolStripMenuItem.Checked = !toolsBarToolStripMenuItem.Checked;
        }

        private void statusBarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            statusStrip1.Visible = !statusBarToolStripMenuItem.Checked;
            statusBarToolStripMenuItem.Checked = !statusBarToolStripMenuItem.Checked;
        }

        private void massFilesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (massFilesToolStripMenuItem.Checked)
                splitContainer1.SplitterDistance=0;
            else
                splitContainer1.SplitterDistance = 310;

            massFilesToolStripMenuItem.Checked = !massFilesToolStripMenuItem.Checked;
        }

        private void invdualFileEditorToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (invdualFileEditorToolStripMenuItem.Checked)
                this.Height = splitContainer1.SplitterDistance + 60;
            else
                this.Height = 600;

            invdualFileEditorToolStripMenuItem.Checked = !invdualFileEditorToolStripMenuItem.Checked;
        }

        private void FilterTree_DragDrop(object sender, DragEventArgs e)
        {
            string[] s = (string[])e.Data.GetData(DataFormats.FileDrop, false);
             ChangesList.Clear();
             M_branch_tree.Nodes.Clear();
             B_tree.Nodes.Clear();
             Opend_Filename = s[1];
             backgroundWorker1.RunWorkerAsync();
                

            
        }

        private void FilterTree_AfterSelect(object sender, TreeViewEventArgs e)
        {

        }

        private void M_branch_tree_DragDrop(object sender, DragEventArgs e)
        {
            string[] s = (string[])e.Data.GetData(DataFormats.FileDrop, false);
            ChangesList.Clear();
            M_branch_tree.Nodes.Clear();
            B_tree.Nodes.Clear();
            Opend_Filename =s[0];
            OFD.FileName = Opend_Filename;
            string filename = Path.GetFileName(Opend_Filename);
            this.Text = "Geo - " + filename;
            backgroundWorker1.RunWorkerAsync();


        }

        private void menuStrip1_MenuActivate(object sender, EventArgs e)
        {
            menuStrip1.Focus();
        }

        private void toolStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (Edittxt.Focused)
            toolStrip1.Focus();
        }

        private void LTStxt_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar)
             && !char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void Split_DGV_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {

            TextBox tb = e.Control as TextBox;
            if (Split_DGV.CurrentCell.ColumnIndex == 2) //Desired Column
            {
                
                e.Control.KeyPress += new KeyPressEventHandler(Column1_KeyPress);
                
                if (tb != null)
                {
                    tb.KeyPress -= new KeyPressEventHandler(Column2_KeyPress);
                    tb.KeyPress += new KeyPressEventHandler(Column1_KeyPress);
                    
                }
                e.Control.KeyPress -= new KeyPressEventHandler(Column1_KeyPress);
            }
            if (Split_DGV.CurrentCell.ColumnIndex == 3) 
            {
                
                e.Control.KeyPress += new KeyPressEventHandler(Column2_KeyPress);
                TextBox tb1 = e.Control as TextBox;
                if (tb != null)
                {
                    tb.KeyPress -= new KeyPressEventHandler(Column1_KeyPress);
                    tb.KeyPress += new KeyPressEventHandler(Column2_KeyPress);
                    
                }
                e.Control.KeyPress -= new KeyPressEventHandler(Column2_KeyPress);
            }

        }
        private void Column1_KeyPress(object sender, KeyPressEventArgs e)
        {

                if (!char.IsControl(e.KeyChar)
                    && !char.IsDigit(e.KeyChar))
                {
                    e.Handled = true;
                }
            
        }
        private void Column2_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar)
                && !char.IsDigit(e.KeyChar)
                && e.KeyChar != ',')
            {
                e.Handled = true;
            }
            int count=0;
            foreach(char comma in (sender as TextBox).Text)
                if (comma==',')
                  count++;

            int part=0;
            if (Split_rb1.Checked)
                part = int.Parse(Split_DGV.CurrentRow.Cells[2].Value.ToString());
            else
                part = 2;


            if ((sender as TextBox).Text.Length >0 )
            {
            if ((sender as TextBox).Text[(sender as TextBox).Text.Length-1].ToString() == "," && e.KeyChar == ',')
            {
                e.Handled = true;
            }
            }
            if (e.KeyChar == ',' && count == part - 1)
            {
                e.Handled = true;
            }
        }

        private void Split_DGV_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (Split_DGV.Columns[e.ColumnIndex].Name == "Parts")
            {
                if (String.IsNullOrEmpty(Split_DGV.Rows[e.RowIndex].Cells[e.ColumnIndex].ToString()))
                {
                    Split_DGV.Rows[e.RowIndex].ErrorText =
                        "Company Name must not be empty";
                    //Split_DGV.Rows[e.RowIndex].Cells[e.ColumnIndex] = "";
                }
            }
        }
    }
}
