using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.IO;

using SmartX;
using INT_LKD_2.Forms;
using INT_LKD_2.DataStore;
using INT_LKD_2.DialogForms;

namespace INT_LKD_2.Controls
{
    public partial class ControlMenuLogInspection : UserControl
    {
        #region Field
        private FormMenu m_ParentForm;
        private string SelectedNodeFullPath;
        private int ListBoxCount;

        private Define.E_DataType CurrentDataType;
        private List<DataBackupYear> ListInspectionFile;

        private Collection<SmartX.SmartListBox> CollectionListBox;
        private Collection<SmartX.SmartLabel> CollectionPassCount;
        private Collection<SmartX.SmartLabel> CollectionLeakCount;
        private List<int> ListPassCount;
        private List<int> ListLeakCount;
        #endregion

        #region Constructor
        public ControlMenuLogInspection(FormMenu parent)
        {
            InitializeComponent();

            this.ParentForm = parent;

            this.Initialize();
            this.DefaultSetting();
        }
        #endregion

        #region Property
        public FormMenu ParentForm
        {
            get { return this.m_ParentForm; }
            private set { this.m_ParentForm = value; }
        }
        #endregion

        #region Method
        private void Initialize()
        {
            this.smartGroupBox1.Text = "Log > Inspection";
        }
        private void DefaultSetting()
        {
            this.CurrentDataType = Define.E_DataType.Inspection;
            this.ListBoxCount = 0;

            this.ListInspectionFile = new List<DataBackupYear>();

            this.CollectionListBox = new Collection<SmartX.SmartListBox>();
            this.CollectionListBox.Clear();
            this.CollectionListBox.Add(this.listBox1);
            this.CollectionListBox.Add(this.listBox2);
            this.CollectionListBox.Add(this.listBox3);
            this.CollectionListBox.Add(this.listBox4);
            this.CollectionListBox.Add(this.listBox5);
            this.CollectionListBox.Add(this.listBox6);
            this.CollectionListBox.Add(this.listBox7);
            this.CollectionListBox.Add(this.listBox8);
            this.CollectionListBox.Add(this.listBox9);
            this.CollectionListBox.Add(this.listBox10);
            this.CollectionListBox.Add(this.listBox11);
            this.CollectionListBox.Add(this.listBox12);

            this.CollectionPassCount = new Collection<SmartX.SmartLabel>();
            this.CollectionPassCount.Clear();
            this.CollectionPassCount.Add(this.labelPassCount1);
            this.CollectionPassCount.Add(this.labelPassCount2);
            this.CollectionPassCount.Add(this.labelPassCount3);
            this.CollectionPassCount.Add(this.labelPassCount4);
            this.CollectionPassCount.Add(this.labelPassCount5);
            this.CollectionPassCount.Add(this.labelPassCount6);
            this.CollectionPassCount.Add(this.labelPassCount7);
            this.CollectionPassCount.Add(this.labelPassCount8);
            this.CollectionPassCount.Add(this.labelPassCount9);
            this.CollectionPassCount.Add(this.labelPassCount10);
            this.CollectionPassCount.Add(this.labelPassCount11);
            this.CollectionPassCount.Add(this.labelPassCount12);

            this.CollectionLeakCount = new Collection<SmartX.SmartLabel>();
            this.CollectionLeakCount.Clear();
            this.CollectionLeakCount.Add(this.labelLeakCount1);
            this.CollectionLeakCount.Add(this.labelLeakCount2);
            this.CollectionLeakCount.Add(this.labelLeakCount3);
            this.CollectionLeakCount.Add(this.labelLeakCount4);
            this.CollectionLeakCount.Add(this.labelLeakCount5);
            this.CollectionLeakCount.Add(this.labelLeakCount6);
            this.CollectionLeakCount.Add(this.labelLeakCount7);
            this.CollectionLeakCount.Add(this.labelLeakCount8);
            this.CollectionLeakCount.Add(this.labelLeakCount9);
            this.CollectionLeakCount.Add(this.labelLeakCount10);
            this.CollectionLeakCount.Add(this.labelLeakCount11);
            this.CollectionLeakCount.Add(this.labelLeakCount12);

            this.ListPassCount = new List<int>();
            for (int i = 0; i < this.ParentForm.ParentForm.SystemConfig.EQUIPMENT_LANE; i++)
                this.ListPassCount.Add(0);

            this.ListLeakCount = new List<int>();
            for (int i = 0; i < this.ParentForm.ParentForm.SystemConfig.EQUIPMENT_LANE; i++)
                this.ListLeakCount.Add(0);
        }

        public void LoadFile(string fullFilePath)
        {
            if (fullFilePath.Contains("_Inspection") == false)
                return;

            this.smartFile1.FilePathName = fullFilePath;
            this.smartFile1.Open();
            this.smartFile1.StringType.EncodingType = SmartX.SmartFile.Encodings.ANSI;

            try
            {
                for (int i = 0; i < this.ParentForm.ParentForm.SystemConfig.EQUIPMENT_LANE; i++)
                    this.ListPassCount[i] = 0;

                for (int i = 0; i < this.ParentForm.ParentForm.SystemConfig.EQUIPMENT_LANE; i++)
                    this.ListLeakCount[i] = 0;

                this.smartFile1.StringType.FillBuffer();

                long lineNum = this.smartFile1.StringType.GetCount();
                this.ListBoxCount = (int)lineNum;
                for (int i = 1; i < lineNum; i++)
                {
                    this.UpdateListBoxDataDisplay(this.smartFile1.StringType.ReadBuffer(i));
                }

                for (int i = 0; i < this.ParentForm.ParentForm.SystemConfig.EQUIPMENT_LANE; i++)
                {
                    this.CollectionPassCount[i].Text = this.ListPassCount[i].ToString();
                    this.CollectionLeakCount[i].Text = this.ListLeakCount[i].ToString();
                }
            }
            catch
            {
                DialogFormMessage myMsg = new DialogFormMessage(16, this.ParentForm.ParentForm.SystemConfig.LANGUAGE);
                myMsg.ShowDialog();

                this.smartFile1.Close();
            }
        
            this.smartFile1.Close();
        }
        private void UpdateListBoxCount()
        {
            this.labelTotalIndex.Text = (this.ListBoxCount - 1).ToString();
            if (this.ListBoxCount - 1 - this.listBoxTime.ViewRemainCount < 0)
                this.labelRemainIndex.Text = "0";
            else
                this.labelRemainIndex.Text = (this.ListBoxCount - 1 - this.listBoxTime.ViewRemainCount).ToString();
        }
        private void UpdateListBoxDataDisplay(string data)
        {
            if (data.Contains(",") == false)
                return;

            string[] sb = data.Split(',');
            string temp = "";

            // Time
            this.listBoxTime.AddItem(sb[1]);

            // 1~10 판정데이터
            for (int i = 0; i < this.ParentForm.ParentForm.SystemConfig.EQUIPMENT_LANE; i++)
            {
                temp = sb[(i * 8) + 4];

                if (temp == "Pass")
                    this.ListPassCount[i]++;
                if (temp == "Leak")
                    this.ListLeakCount[i]++;

                this.CollectionListBox[i].AddItem(sb[(i * 8) + 4]);
            }
        }
        private void UpdateDisplayFile()
        {
            int fileCount = 0;
            //TreeNode node;
            List<string> years = new List<string>();
            List<string> months = new List<string>();
            List<string> days = new List<string>();

            this.treeViewInspection.Nodes.Clear();
            this.ListInspectionFile.Clear();

            DirectoryInfo dir = new DirectoryInfo(this.ParentForm.ParentForm.PathDataInspectionFolder);
            List<string> fileNames = new List<string>();

            // 폴더 체크
            if (dir.Exists == false)
                dir.Create();

            // year 폴더 가져오기
            DirectoryInfo[] yearDirectorys = dir.GetDirectories();
            // year 폴더 정렬 
            years = this.ParentForm.DirectorySort(yearDirectorys);

            // Inspection File 리스트 생성
            if (years.Count != 0)
            {
                // Year
                foreach (string year in years)
                {
                    DataBackupYear y = new DataBackupYear(year);
                    DirectoryInfo monthDir = new DirectoryInfo(string.Format("{0}{1}", this.ParentForm.ParentForm.PathDataInspectionFolder, year));
                    DirectoryInfo[] monthDirectorys = monthDir.GetDirectories();

                    months = this.ParentForm.DirectorySort(monthDirectorys);

                    if (months.Count != 0)
                    {
                        // Month
                        foreach (string month in months)
                        {
                            DirectoryInfo dayDir = new DirectoryInfo(string.Format("{0}{1}\\{2}", this.ParentForm.ParentForm.PathDataInspectionFolder, year, month));
                            FileInfo[] dayFiles = dayDir.GetFiles();

                            days = this.DayInspectionDirectorySort(dayFiles);

                            DataBackupMonth m = new DataBackupMonth(month);
                            m.Days = days;

                            y.Months.Add(m);
                        }

                        this.ListInspectionFile.Add(y);
                    }
                    else
                    {
                        this.ListInspectionFile.Add(y);
                    }
                }

                // node 생성
                for (int i = 0; i < this.ListInspectionFile.Count; i++)
                {
                    TreeNode node = new TreeNode(this.ListInspectionFile[i].Year);
                    for (int j = 0; j < this.ListInspectionFile[i].Months.Count; j++)
                    {
                        TreeNode nodeMonth = new TreeNode(this.ListInspectionFile[i].Months[j].Month);

                        for (int k = 0; k < this.ListInspectionFile[i].Months[j].Days.Count; k++)
                        {
                            nodeMonth.Nodes.Add(this.ListInspectionFile[i].Months[j].Days[k]);
                            fileCount++;
                        }
                        node.Nodes.Add(nodeMonth);
                    }
                    this.treeViewInspection.Nodes.Add(node);
                }
            }

            this.labelCount.Text = fileCount.ToString();
        }
        private List<string> DayInspectionDirectorySort(FileInfo[] files)
        {
            StringBuilder sb;
            List<string> listFile = new List<string>();
            Dictionary<string, int> dirNames = new Dictionary<string, int>();

            #region File List 품번 순서대로 정렬
            foreach (FileInfo file in files)
            {
                sb = new StringBuilder();

                for (int i = 20; i < file.Name.IndexOf("."); i++)
                    sb.Append(file.Name.Substring(i, 1));

                dirNames.Add(file.Name, int.Parse(file.Name.Substring(20, 1)));
            }

            var vrList = dirNames.OrderBy(x => x.Value);
            foreach (var v in vrList)
                listFile.Add(v.Key);
            #endregion

            #region File List 날짜 순서대로 정렬
            dirNames = new Dictionary<string, int>();
            foreach (string f in listFile)
                dirNames.Add(f, int.Parse(f.Substring(0, 8)));

            listFile.Clear();
            vrList = dirNames.OrderBy(x => x.Value);
            foreach (var v in vrList)
                listFile.Add(v.Key);
            #endregion

            return listFile;
        }

        public void DisplayRefresh()
        {
            this.ParentForm.ParentForm.CurrentSystemStatus.CurrentDisplayMode = Define.E_DisplayModeStore.LogInspection;
            this.ParentForm.ParentForm.SetDisplayMode(Define.E_EquipmentMode.Menu);

            this.UpdateDisplayFile();
            this.treeViewInspection.ExpandAll();

            this.labelRemainIndex.Text = "0";
            this.labelTotalIndex.Text = "0";
            this.ListBoxCount = 0;
            for (int i = 0; i < this.ParentForm.ParentForm.SystemConfig.EQUIPMENT_LANE; i++)
            {
                this.CollectionPassCount[i].Text = "0";
                this.CollectionLeakCount[i].Text = "0";
            }

            // User
            switch (this.ParentForm.ParentForm.CurrentSystemStatus.CurrentUser.Group)
            {
                case Define.E_UserGroup.None:
                    this.Enabled = false;
                    break;
                case Define.E_UserGroup.Level1:
                    this.Enabled = this.ParentForm.ParentForm.CurrentUserGroup.Level1.IsMenuAlarmLog;
                    break;
                case Define.E_UserGroup.Level2:
                    this.Enabled = this.ParentForm.ParentForm.CurrentUserGroup.Level2.IsMenuAlarmLog;
                    break;
                case Define.E_UserGroup.Level3:
                    this.Enabled = this.ParentForm.ParentForm.CurrentUserGroup.Level3.IsMenuAlarmLog;
                    break;
                case Define.E_UserGroup.Admin:
                    this.Enabled = this.ParentForm.ParentForm.CurrentUserGroup.Level3.IsMenuAlarmLog;
                    break;
                case Define.E_UserGroup.Developer:
                    this.Enabled = true;
                    break;
                case Define.E_UserGroup.NotLogin:
                    this.Enabled = false;
                    break;
                case Define.E_UserGroup.LogOut:
                    this.Enabled = false;
                    break;
                default:
                    break;
            }
        }
        #endregion

        #region Event Handler
        private void treeViewInspection_AfterSelect(object sender, TreeViewEventArgs e)
        {
            this.labelFileName.Text = e.Node.Text;
            this.SelectedNodeFullPath = this.treeViewInspection.SelectedNode.FullPath;
            for (int i = 0; i < this.ParentForm.ParentForm.SystemConfig.EQUIPMENT_LANE; i++)
                this.CollectionListBox[i].ClearAll();
            this.listBoxTime.ClearAll();

            this.LoadFile(this.ParentForm.ParentForm.PathDataInspectionFolder + this.treeViewInspection.SelectedNode.FullPath);

            this.UpdateListBoxCount();
        }
        private void buttonBackup_Click(object sender, EventArgs e)
        {
            if (this.labelFileName.Text == "")
                return;

            this.ParentForm.FileCopy(Define.E_DataType.Inspection, this.SelectedNodeFullPath);
        }

        private void buttonUp_Click(object sender, EventArgs e)
        {
            this.listBoxTime.ScrollUp();

            for (int i = 0; i < this.ParentForm.ParentForm.SystemConfig.EQUIPMENT_LANE; i++)
                this.CollectionListBox[i].ScrollUp();

            this.UpdateListBoxCount();
        }
        private void buttonDown_Click(object sender, EventArgs e)
        {
            this.listBoxTime.ScrollDown();

            for (int i = 0; i < this.ParentForm.ParentForm.SystemConfig.EQUIPMENT_LANE; i++)
                this.CollectionListBox[i].ScrollDown();

            this.UpdateListBoxCount();
        }
        #endregion
    }
}
