using ManualSoftwareSystem.lib;
using ManualSoftwareSystem.Operation_Manual;
using ManualSoftwareSystem.Work_History;
//using Microsoft.Office.Interop.Excel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.AccessControl;
using System.Security.Permissions;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Net.Mime.MediaTypeNames;

namespace ManualSoftwareSystem.Search_Function
{
    public partial class FrmSearchFunction : Form
    {
        private List<List<string>> Data = new List<List<string>>();
        private string csvPartFileSearchFunction = System.IO.Directory.GetCurrentDirectory() + "\\SearchFunction.sys";
        public dynamic objLanguage;

        public FrmSearchFunction()
        {
            InitializeComponent();
            this.objLanguage = FrmOperationManualOperator.objLanguage;
        }

        private void FrmSearchFunction_Load(object sender, EventArgs e)
        {
            string strSearchFunction = "Search Function";
            string strWorkHistory = "Work history";
            string strCompletionResults = "Completion results";
            string strWorking = "Working";
            string strError = "Error";
            string strSearch = "Search";
            string strClear = "Clear";
            string strAddSearchFunction = "Add";
            string strDelSearchFunction = "Del";

            lblSearchFunction.Text = objLanguage.Translate(strSearchFunction);
            rbnWorkHistory.Text = objLanguage.Translate(strWorkHistory);
            rbnCompletionResults.Text = objLanguage.Translate(strCompletionResults);
            rbnWorking.Text = objLanguage.Translate(strWorking);
            rbnError.Text = objLanguage.Translate(strError);
            btnSearch.Text = objLanguage.Translate(strSearch);
            btnClear.Text = objLanguage.Translate(strClear);
            btnAddSearchFunction.Text = objLanguage.Translate(strAddSearchFunction);
            btnDelSearchFunction.Text = objLanguage.Translate(strDelSearchFunction);


            if (!File.Exists(csvPartFileSearchFunction))
            {
                using (StreamWriter sw = File.CreateText(csvPartFileSearchFunction))
                {
                    //sw.WriteLine("");
                }
            }

            cmbSearchFunction.Items.Clear();

            List<string> tmp = null;
            Data = new List<List<string>>();
            tmp = null;
            Int32 i = 0;
            using (var csv = new CsvReader(csvPartFileSearchFunction))
            {
                while ((tmp = csv.ReadRow()) != null)
                {
                    Data.Add(tmp);

                    if (i == 0)
                    {
                        for (int j = 0; j < tmp.Count; j++)
                        {
                            if (this.Data[0][j] != string.Empty)
                            {
                                cmbSearchFunction.Items.Add(this.Data[0][j]);
                            }

                        }
                    }

                    i = i + 1;
                }

            }//using end
        }

        private void btnAddSearchFunction_Click(object sender, EventArgs e)
        {
            if (cmbSearchFunction.Text.Trim().Replace(",", "") == string.Empty)
            {
                MessageBox.Show(this, objLanguage.Translate("Search is Blanks"),
                                       objLanguage.Translate("Warning"), MessageBoxButtons.OK,
                                       MessageBoxIcon.Exclamation,
                                       MessageBoxDefaultButton.Button1, 0);
                return;
            }


            int index = cmbSearchFunction.FindStringExact(cmbSearchFunction.Text.Trim().Replace(",", ""));

            if (index == -1)
            {
                cmbSearchFunction.Items.Add(cmbSearchFunction.Text.Trim().Replace(",", ""));

                //CSV Encoding
                System.Text.Encoding enc =
                    System.Text.Encoding.UTF8;

                System.IO.StreamWriter sr =
                    new System.IO.StreamWriter(csvPartFileSearchFunction, false, enc);

                for (int i = 0; i < cmbSearchFunction.Items.Count; i++)
                {
                    sr.WriteLine(cmbSearchFunction.Items[i]);
                }

                sr.Close();


                //string strTemp = string.Empty;

                //for (int i = 0; i < cmbSearchFunction.Items.Count; i++)
                //{
                //    if (i == 0)
                //    {
                //        strTemp = cmbSearchFunction.Items[i].ToString();
                //    }
                //    else
                //    {
                //        strTemp = strTemp + "," + cmbSearchFunction.Items[i].ToString();
                //    }

                //}


                //lineChanger(strTemp, csvPartFileSearchFunction, 1);

            }
        }

        static void lineChanger(string newText, string fileName, int line_to_edit)
        {
            string[] arrLine = File.ReadAllLines(fileName);
            arrLine[line_to_edit - 1] = newText;
            File.WriteAllLines(fileName, arrLine);
        }

        private void btnDelSearchFunction_Click(object sender, EventArgs e)
        {
            if (cmbSearchFunction.Text.Trim() == string.Empty)
            {
                //MessageBox.Show(this, objLanguage.Translate("Detailed Comment is Blanks"),
                MessageBox.Show(this, objLanguage.Translate("Error details is Blanks"),
                                   objLanguage.Translate("Warning"), MessageBoxButtons.OK,
                                   MessageBoxIcon.Exclamation,
                                   MessageBoxDefaultButton.Button1, 0);
                return;
            }

            int index = cmbSearchFunction.FindStringExact(cmbSearchFunction.Text.Trim());

            if (index > -1)
            {
                cmbSearchFunction.Items.RemoveAt(index);

                //CSV Encoding
                System.Text.Encoding enc =
                    System.Text.Encoding.UTF8;

                System.IO.StreamWriter sr =
                    new System.IO.StreamWriter(csvPartFileSearchFunction, false, enc);

                for (int i = 0; i < cmbSearchFunction.Items.Count; i++)
                {
                    sr.WriteLine(cmbSearchFunction.Items[i]);
                }

                sr.Close();

                cmbSearchFunction.Text = string.Empty;


                //if (cmbSearchFunction.Items.Count == 0)
                //{
                //    cmbSearchFunction.Items.Clear();
                //    cmbSearchFunction.Text = string.Empty;
                //}

                //string strTemp = string.Empty;

                //for (int i = 0; i < cmbSearchFunction.Items.Count; i++)
                //{
                //    if (i == 0)
                //    {
                //        strTemp = cmbSearchFunction.Items[i].ToString();
                //    }
                //    else
                //    {
                //        strTemp = strTemp + "," + cmbSearchFunction.Items[i].ToString();
                //    }

                //}

                //if (strTemp == string.Empty)
                //{                    
                //    strTemp = "\n";
                //}

                //lineChanger(strTemp, csvPartFileSearchFunction, 1);
            }
        }

        private void btnOrderAtoZSearchFunction_Click(object sender, EventArgs e)
        {
            cmbSearchFunction.Sorted = true;
        }

        private void btnOrderZtoASearchFunction_Click(object sender, EventArgs e)
        {
            cmbSearchFunction.Sorted = false;

            List<string> TempList = new List<string>();
            for (int i = 0; i < cmbSearchFunction.Items.Count; i++)
            {

                TempList.Add(cmbSearchFunction.Items[i].ToString());

            }

            List<string> sortedDetailedComment = TempList.OrderByDescending(DetailedComment => DetailedComment).ToList();
            cmbSearchFunction.Items.Clear();
            foreach (string DetailedCommentName in sortedDetailedComment)
                cmbSearchFunction.Items.Add(DetailedCommentName);
        }

        private void cmbSearchFunction_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == ',')
            {
                e.Handled = true;
            }
        }




        //private string[] GetFiles(string path, string searchPattern)
        //{
        //    var files = new List<string>();
        //    try
        //    {
        //        foreach (string str in Directory.GetFiles("C:\\", "*.*", SearchOption.AllDirectories))
        //        {
        //            FileInfo fi = new FileInfo(str);
        //            if (fi.Extension == "*.csv")
        //            {

        //            }
        //            else
        //            {
        //                files.Add(str);
        //            }
        //        }



        //        files.AddRange(Directory.GetFiles(path, searchPattern));

        //        foreach (string subfolder in Directory.GetDirectories(path))
        //        {
        //            files.AddRange(GetFiles(subfolder, searchPattern));
        //        }

        //    }
        //    catch (UnauthorizedAccessException)
        //    {

        //    }
        //    return files.ToArray();
        //}

        bool isDriveExists(string driveLetterWithColonAndSlash)
        {
            return DriveInfo.GetDrives().Any(x => x.Name == driveLetterWithColonAndSlash);
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            //var files = Directory.EnumerateFiles("C:\\", "*.csv", SearchOption.AllDirectories);

            //var files = GetFiles("C:\\", "*.csv");

            Cursor = Cursors.WaitCursor;

            var files = new List<string>();
            var directorys = new List<string>();
            var driveList = new List<string>();

            string textSearch = cmbSearchFunction.Text.Trim();
            string strType = string.Empty;


            var options = new EnumerationOptions()
            {
                IgnoreInaccessible = true
            };

            if (isDriveExists("C:\\"))
            {
                driveList.Add("C:\\");
            }
            if (isDriveExists("D:\\"))
            {
                driveList.Add("D:\\");
            }
            if (isDriveExists("E:\\"))
            {
                driveList.Add("E:\\");
            }
            if (isDriveExists("F:\\"))
            {
                driveList.Add("F:\\");
            }
            if (isDriveExists("G:\\"))
            {
                driveList.Add("G:\\");
            }
            if (isDriveExists("H:\\"))
            {
                driveList.Add("H:\\");
            }
            if (isDriveExists("I:\\"))
            {
                driveList.Add("I:\\");
            }
            if (isDriveExists("J:\\"))
            {
                driveList.Add("J:\\");
            }
            if (isDriveExists("K:\\"))
            {
                driveList.Add("K:\\");
            }
            if (isDriveExists("L:\\"))
            {
                driveList.Add("L:\\");
            }
            if (isDriveExists("M:\\"))
            {
                driveList.Add("M:\\");
            }
            if (isDriveExists("N:\\"))
            {
                driveList.Add("N:\\");
            }
            if (isDriveExists("O:\\"))
            {
                driveList.Add("O:\\");
            }
            if (isDriveExists("P:\\"))
            {
                driveList.Add("P:\\");
            }
            if (isDriveExists("Q:\\"))
            {
                driveList.Add("Q:\\");
            }
            if (isDriveExists("R:\\"))
            {
                driveList.Add("R:\\");
            }
            if (isDriveExists("S:\\"))
            {
                driveList.Add("S:\\");
            }
            if (isDriveExists("T:\\"))
            {
                driveList.Add("T:\\");
            }
            if (isDriveExists("U:\\"))
            {
                driveList.Add("U:\\");
            }
            if (isDriveExists("V:\\"))
            {
                driveList.Add("V:\\");
            }
            if (isDriveExists("W:\\"))
            {
                driveList.Add("W:\\");
            }
            if (isDriveExists("X:\\"))
            {
                driveList.Add("X:\\");
            }
            if (isDriveExists("Y:\\"))
            {
                driveList.Add("Y:\\");
            }
            if (isDriveExists("Z:\\"))
            {
                driveList.Add("Z:\\");
            }


            foreach (string strDriveList in driveList)
            {
                DirectoryInfo d = new DirectoryInfo(strDriveList);
                directorys.Add(strDriveList);

                //DirectoryInfo d = new DirectoryInfo("C:\\");
                //DirectoryInfo d = new DirectoryInfo("C:\\Checkru\\");

                //directorys.Add("C:\\");
                //directorys.Add("C:\\Checkru");

                foreach (DirectoryInfo directory in d.GetDirectories())
                {
                    directorys.Add(directory.FullName.ToString());
                    if ((directory.Attributes & FileAttributes.Hidden) != FileAttributes.Hidden)
                    {

                        foreach (string subDir in Directory.GetDirectories(directory.FullName.ToString()))
                        {
                            try
                            {
                                directorys.Add(subDir);

                                //if ((directory.FullName.ToString() != "C:\\inetpub") && (directory.FullName.ToString() != "C:\\Program Files")
                                //    && (directory.FullName.ToString() != "C:\\Program Files (x86)"))
                                //{
                                //    //directorys.Add(directory.FullName.ToString());
                                //    directorys.Add(subDir);
                                //}

                            }
                            catch
                            {
                                continue;
                            }

                        }


                        //if ((directory.FullName.ToString() != "C:\\inetpub") && (directory.FullName.ToString() != "C:\\Program Files")
                        //    && (directory.FullName.ToString() != "C:\\Program Files (x86)"))
                        //{
                        //    directorys.Add(directory.FullName.ToString());
                        //}
                    }
                }
            }

            if (rbnWorkHistory.Checked == true)
            {
                strType = "csv";

                if (string.IsNullOrEmpty(textSearch))
                {

                    try
                    {
                        foreach (string str in directorys)
                        {
                            try
                            {


                                //foreach (string str1 in Directory.GetFiles(str + "\\", "*.csv", SearchOption.AllDirectories))
                                foreach (string str1 in Directory.GetFiles(str + "\\", "*.csv", options))
                                {
                                    try
                                    {
                                        FileInfo fi = new FileInfo(str1);
                                        if (fi.Extension == ".csv")
                                        {
                                            if (files.Contains(str1) == false)
                                            {
                                                files.Add(str1);
                                            }

                                        }
                                        else
                                        {

                                        }
                                    }
                                    catch
                                    {
                                        continue;
                                    }
                                }
                            }
                            catch
                            {

                                continue;
                            }
                        }
                    }
                    catch (UnauthorizedAccessException)
                    {

                    }
                }
                else
                {
                    try
                    {
                        foreach (string str in directorys)
                        {
                            try
                            {
                                //foreach (string str1 in Directory.GetFiles(str + "\\", "*" + cmbSearchFunction.Text.Trim() + "*.csv", SearchOption.AllDirectories))
                                foreach (string str1 in Directory.GetFiles(str + "\\", "*" + cmbSearchFunction.Text.Trim() + "*.csv", options))
                                {
                                    try
                                    {
                                        FileInfo fi = new FileInfo(str1);
                                        if (fi.Extension == ".csv")
                                        {
                                            //files.Add(str1);
                                            if (files.Contains(str1) == false)
                                            {
                                                files.Add(str1);
                                            }
                                        }
                                        else
                                        {

                                        }
                                    }
                                    catch
                                    {
                                        continue;
                                    }
                                }
                            }
                            catch
                            {

                                continue;
                            }
                        }

                    }
                    catch (UnauthorizedAccessException)
                    {

                    }
                }
            }
            else if (rbnCompletionResults.Checked == true)
            {
                strType = "001";
                if (string.IsNullOrEmpty(textSearch))
                {
                    try
                    {
                        foreach (string str in directorys)
                        {
                            try
                            {
                                //foreach (string str1 in Directory.GetFiles(str + "\\", "*.001", SearchOption.AllDirectories))
                                foreach (string str1 in Directory.GetFiles(str + "\\", "*.001", options))
                                {
                                    try
                                    {
                                        FileInfo fi = new FileInfo(str1);
                                        if (fi.Extension == ".001")
                                        {
                                            //files.Add(str1);
                                            if (files.Contains(str1) == false)
                                            {
                                                files.Add(str1);
                                            }
                                        }
                                        else
                                        {

                                        }
                                    }
                                    catch
                                    {
                                        continue;
                                    }
                                }
                            }
                            catch
                            {

                                continue;
                            }
                        }
                    }
                    catch (UnauthorizedAccessException)
                    {

                    }
                }
                else
                {
                    try
                    {
                        foreach (string str in directorys)
                        {
                            try
                            {
                                //foreach (string str1 in Directory.GetFiles(str + "\\", "*" + cmbSearchFunction.Text.Trim() + "*.001", SearchOption.AllDirectories))
                                foreach (string str1 in Directory.GetFiles(str + "\\", "*" + cmbSearchFunction.Text.Trim() + "*.001", options))
                                {
                                    try
                                    {
                                        FileInfo fi = new FileInfo(str1);
                                        if (fi.Extension == ".001")
                                        {
                                            //files.Add(str1);
                                            if (files.Contains(str1) == false)
                                            {
                                                files.Add(str1);
                                            }
                                        }
                                        else
                                        {

                                        }
                                    }
                                    catch
                                    {
                                        continue;
                                    }
                                }
                            }
                            catch
                            {

                                continue;
                            }
                        }

                    }
                    catch (UnauthorizedAccessException)
                    {

                    }
                }
            }
            else if (rbnWorking.Checked == true)
            {
                strType = "000";
                if (string.IsNullOrEmpty(textSearch))
                {
                    try
                    {
                        foreach (string str in directorys)
                        {
                            try
                            {
                                //foreach (string str1 in Directory.GetFiles(str + "\\", "*.000", SearchOption.AllDirectories))
                                foreach (string str1 in Directory.GetFiles(str + "\\", "*.000", options))
                                {
                                    try
                                    {
                                        FileInfo fi = new FileInfo(str1);
                                        if (fi.Extension == ".000")
                                        {
                                            //files.Add(str1);
                                            if (files.Contains(str1) == false)
                                            {
                                                files.Add(str1);
                                            }
                                        }
                                        else
                                        {

                                        }
                                    }
                                    catch
                                    {
                                        continue;
                                    }
                                }
                            }
                            catch
                            {

                                continue;
                            }
                        }
                    }
                    catch (UnauthorizedAccessException)
                    {

                    }
                }
                else
                {
                    try
                    {
                        foreach (string str in directorys)
                        {
                            try
                            {
                                //foreach (string str1 in Directory.GetFiles(str + "\\", "*" + cmbSearchFunction.Text.Trim() + "*.000", SearchOption.AllDirectories))
                                foreach (string str1 in Directory.GetFiles(str + "\\", "*" + cmbSearchFunction.Text.Trim() + "*.000", options))
                                {
                                    try
                                    {
                                        FileInfo fi = new FileInfo(str1);
                                        if (fi.Extension == ".000")
                                        {
                                            //files.Add(str1);
                                            if (files.Contains(str1) == false)
                                            {
                                                files.Add(str1);
                                            }
                                        }
                                        else
                                        {

                                        }
                                    }
                                    catch
                                    {
                                        continue;
                                    }
                                }
                            }
                            catch
                            {

                                continue;
                            }
                        }

                    }
                    catch (UnauthorizedAccessException)
                    {

                    }
                }
            }
            else if (rbnError.Checked == true)
            {
                strType = "002";
                if (string.IsNullOrEmpty(textSearch))
                {
                    try
                    {
                        foreach (string str in directorys)
                        {
                            try
                            {
                                //foreach (string str1 in Directory.GetFiles(str + "\\", "*.002", SearchOption.AllDirectories))
                                foreach (string str1 in Directory.GetFiles(str + "\\", "*.002", options))
                                {
                                    try
                                    {
                                        FileInfo fi = new FileInfo(str1);
                                        if (fi.Extension == ".002")
                                        {
                                            //files.Add(str1);
                                            if (files.Contains(str1) == false)
                                            {
                                                files.Add(str1);
                                            }
                                        }
                                        else
                                        {

                                        }
                                    }
                                    catch
                                    {
                                        continue;
                                    }
                                }
                            }
                            catch
                            {

                                continue;
                            }
                        }
                    }
                    catch (UnauthorizedAccessException)
                    {

                    }
                }
                else
                {
                    try
                    {
                        foreach (string str in directorys)
                        {
                            try
                            {
                                //foreach (string str1 in Directory.GetFiles(str + "\\", "*" + cmbSearchFunction.Text.Trim() + "*.002", SearchOption.AllDirectories))
                                foreach (string str1 in Directory.GetFiles(str + "\\", "*" + cmbSearchFunction.Text.Trim() + "*.002", options))
                                {
                                    try
                                    {
                                        FileInfo fi = new FileInfo(str1);
                                        if (fi.Extension == ".002")
                                        {
                                            //files.Add(str1);
                                            if (files.Contains(str1) == false)
                                            {
                                                files.Add(str1);
                                            }
                                        }
                                        else
                                        {

                                        }
                                    }
                                    catch
                                    {
                                        continue;
                                    }
                                }
                            }
                            catch
                            {

                                continue;
                            }
                        }

                    }
                    catch (UnauthorizedAccessException)
                    {

                    }
                }
            }


            DataTable dt = new DataTable();
            dt.Columns.Add(objLanguage.Translate("Date Time"));
            dt.Columns.Add(objLanguage.Translate("File Type"));
            dt.Columns.Add(objLanguage.Translate("File Name"));

            //try
            //{
            foreach (var file in files)
            {

                var lastModified = System.IO.File.GetLastWriteTime(file);
                string strDateTime = lastModified.ToString("yyyy/MM/dd HH:mm:ss");

                string strLine = strDateTime + "," + strType + "," + file;
                string[] strArray;
                strArray = strLine.Split(',');
                dt.Rows.Add(strArray);


            }

            //}
            //catch (UnauthorizedAccessException) { throw; } //Discard

            dataGridView1.DataSource = dt;


            dataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            dataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            dataGridView1.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

            dataGridView1.Columns[0].SortMode = DataGridViewColumnSortMode.NotSortable;
            dataGridView1.Columns[1].SortMode = DataGridViewColumnSortMode.NotSortable;
            dataGridView1.Columns[2].SortMode = DataGridViewColumnSortMode.NotSortable;


            //dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

            Cursor = Cursors.Default;

        }

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {

            if (e.RowIndex == -1)
            {
                return;
            }

            if ((dataGridView1.Rows[e.RowIndex].Cells[2]).Value == null)
            {
                return;
            }

            if ((dataGridView1.Rows[e.RowIndex].Cells[2]).Value.ToString() == string.Empty)
            {
                return;
            }
            if ((dataGridView1.Rows[e.RowIndex].Cells[1]).Value.ToString() == "csv")
            {
                FrmWorkHistoryViewer frmWorkHistoryViewer = new FrmWorkHistoryViewer((dataGridView1.Rows[e.RowIndex].Cells[2]).Value.ToString());
                frmWorkHistoryViewer.ShowDialog();
            }
            else
            {
                FrmSearchViewer frmSearchViewer = new FrmSearchViewer((dataGridView1.Rows[e.RowIndex].Cells[2]).Value.ToString());
                frmSearchViewer.ShowDialog();

            }

        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            cmbSearchFunction.Text = string.Empty;
            dataGridView1.DataSource = dt;
            dataGridView1.Refresh();
        }

        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            var grid = sender as DataGridView;
            var rowIdx = (e.RowIndex + 1).ToString();

            var centerFormat = new StringFormat()
            {
                // right alignment might actually make more sense for numbers
                Alignment = StringAlignment.Center,
                LineAlignment = StringAlignment.Center
            };

            var headerBounds = new Rectangle(e.RowBounds.Left, e.RowBounds.Top, grid.RowHeadersWidth, e.RowBounds.Height);
            e.Graphics.DrawString(rowIdx, this.Font, SystemBrushes.ControlText, headerBounds, centerFormat);
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }
    }
}
