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

using SmartX;
using INT_PT002.Forms;
using INT_PT002.DataStore;
using INT_PT002.DialogForms;

namespace INT_PT002.Controls
{
    public partial class ControlMenuLogHistory : UserControl
    {
        #region Field
        private FormMenu m_ParentForm;

        private Define.E_DataType SelecteDataType;
        private List<DataBackupYear> ListHistoryFile;
        #endregion

        #region Constructor
        public ControlMenuLogHistory(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 > History";
        }
        private void DefaultSetting()
        {
            this.SelecteDataType = Define.E_DataType.None;

            this.ListHistoryFile = new List<DataBackupYear>();
        }

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

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

            try
            {
                this.smartFile1.StringType.FillBuffer();

                long lineNum = this.smartFile1.StringType.GetCount();
                for (int i = 1; i < lineNum; i++)
                {
                    this.listBox.AddItem(this.smartFile1.StringType.ReadBuffer(i));
                }
            }
            catch
            {
                DialogFormMessage myMsg = new DialogFormMessage(16, this.ParentForm.ParentForm.SystemConfig.LANGUAGE);
                myMsg.ShowDialog();

                this.smartFile1.Close();
            }

            this.smartFile1.Close();
        }
        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.treeView.Nodes.Clear();
            this.ListHistoryFile.Clear();

            DirectoryInfo dir = new DirectoryInfo(this.ParentForm.ParentForm.PathDataHistoryFolder);
            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.PathDataHistoryFolder, 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.PathDataHistoryFolder, year, month));
                            FileInfo[] dayFiles = dayDir.GetFiles();

                            days = this.DayHistoryDirectorySort(dayFiles);

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

                            y.Months.Add(m);
                        }

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

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

                        for (int k = 0; k < this.ListHistoryFile[i].Months[j].Days.Count; k++)
                        {
                            nodeMonth.Nodes.Add(this.ListHistoryFile[i].Months[j].Days[k]);
                            fileCount++;
                        }
                        node.Nodes.Add(nodeMonth);
                    }
                    this.treeView.Nodes.Add(node);
                }
            }
            this.labelCount.Text = fileCount.ToString();
        }

        private List<string> DayHistoryDirectorySort(FileInfo[] files)
        {
            List<string> listFile = new List<string>();
            Dictionary<string, int> dirNames = new Dictionary<string, int>();
            Dictionary<string, int> dirNamesSort = new Dictionary<string, int>();

            foreach (FileInfo file in files)
            {
                if (file.Name.StartsWith("20") == true)
                    dirNames.Add(file.Name, int.Parse(file.Name.Substring(0, 8)));
            }

            var vrList = dirNames.Keys.ToList();
            vrList.Sort();

            foreach (var v in vrList)
                dirNamesSort.Add(v, dirNames[v]);

            foreach (var v in dirNamesSort)
                listFile.Add(v.Key);

            return listFile;
        }

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

            this.SelecteDataType = Define.E_DataType.None;

            this.UpdateDisplayFile();
            this.treeView.ExpandAll();

            if (int.Parse(this.labelCount.Text) == 0)
            {
                DialogFormMessage msg = new DialogFormMessage(36, this.ParentForm.ParentForm.SystemConfig.LANGUAGE);
                msg.ShowDialog();
                return;
            }
        }
        #endregion

        #region Event Handler
        private void treeViewHistory_AfterSelect(object sender, TreeViewEventArgs e)
        {
            this.labelFileName.Text = e.Node.Text;
            this.LoadFile(this.ParentForm.ParentForm.PathDataHistoryFolder + this.treeView.SelectedNode.FullPath);
        }
        #endregion
    }
}
