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

using INT69DC_7C.Forms;

namespace INT69DC_7C.DialogForms
{
    public partial class DialogFormHistoryData : Form
    {
        #region Field
        private FormDataViewer m_ParentForm;
        private string SeletedFilePath;
        #endregion
        
        #region Constructor
        public DialogFormHistoryData(FormDataViewer parent)
        {
            InitializeComponent();

            this.ParentForm = parent;

            this.InitializeDesign();
            this.InitializeContnrol();
            this.DefaultSetting();
        } 
        #endregion

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

        #region Method
        private void InitializeDesign()
        {
            if (this.ParentForm.ParentForm.SystemConfig.Language == DataStore.LanguageID.Chinese)
            {
                this.labelTitleDate.Text = "日期";

                this.buttonRead.Text = "读取";
                this.buttonClose.Text = "关闭";
            }
            else if (this.ParentForm.ParentForm.SystemConfig.Language == DataStore.LanguageID.Czech)
            {
                this.labelTitleDate.Text = "Datum";

                this.buttonRead.Text = "Přečíst vše";
                this.buttonClose.Text = "Zavřít";
            }
            else if (this.ParentForm.ParentForm.SystemConfig.Language == DataStore.LanguageID.German)
            {
                this.labelTitleDate.Text = "Datum";

                this.buttonRead.Text = "Alles lesen";
                this.buttonClose.Text = "Schließen";
            }
            else if (this.ParentForm.ParentForm.SystemConfig.Language == DataStore.LanguageID.Japanese)
            {
                this.labelTitleDate.Text = "日付";

                this.buttonRead.Text = "読む";
                this.buttonClose.Text = "クロㅡズ";
            }
            else
            {

            }
        }
        private void InitializeContnrol()
        {
            int x = 0, y = 0;

            x = Screen.PrimaryScreen.Bounds.Width / 2 - this.Size.Width / 2;
            y = Screen.PrimaryScreen.Bounds.Height / 2 - this.Size.Height / 2;

            this.Location = new Point(x, y);
            this.Size = new Size(350, 470);
        }
        private void DefaultSetting()
        {
            this.DisplayTreeViewUpdate();

            this.checkBoxTypeAlarm.Checked = this.ParentForm.ParentForm.CurrentDataViewerFilter.TypeAlarm;
            this.checkBoxTypeOperation.Checked = this.ParentForm.ParentForm.CurrentDataViewerFilter.TypeOperation;
            this.checkBoxTypeParameter.Checked = this.ParentForm.ParentForm.CurrentDataViewerFilter.TypeParameter;

            this.labelNodeIndex.Text = "-";
            this.labelFileName.Text = "-";
            this.labelDate.Text = "-";
            this.SeletedFilePath = "";
        }

        private List<string> DirectorySort(DirectoryInfo[] directorys)
        {
            List<string> listDirectory = new List<string>();
            Dictionary<string, int> dirNames = new Dictionary<string, int>();

            foreach (DirectoryInfo dir in directorys)
                dirNames.Add(dir.Name, int.Parse(dir.Name));

            // 순서데로 오름차순 정렬
            var vrList = dirNames.OrderBy(x => x.Value);
            foreach (var v in vrList)
                listDirectory.Add(v.Key);

            return listDirectory;
        }
        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("H") == true)
                    dirNames.Add(file.Name, int.Parse(file.Name.Substring(1, 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;
        }
 
        private void DisplayTreeViewUpdate()
        {
            int fileCount = 0;
            string[] fileName;
            //TreeNode node;
            List<DataBackupYear> listHistoryFile = new List<DataBackupYear>();
            List<string> years = new List<string>();
            List<string> months = new List<string>();
            List<string> days = new List<string>();

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

                        listHistoryFile.Add(y);
                    }
                    else
                    {
                        listHistoryFile.Add(y);
                    }
                }

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

                        for (int k = 0; k < listHistoryFile[i].Months[j].Days.Count; k++)
                        {
                            fileName = listHistoryFile[i].Months[j].Days[k].Split('.');
                            nodeMonth.Nodes.Add(fileName[0]);
                            fileCount++;
                        }
                        node.Nodes.Add(nodeMonth);
                    }
                    this.treeView.Nodes.Add(node);
                }

                //try
                //{
                //    if (this.treeView.SelectedNode.IsSelected == true)
                //        this.treeView.SelectedNode.Parent.Expand();
                //}
                //catch
                //{

                //}
            }
        }
        #endregion

        #region Event Handler
        private void buttonRead_Click(object sender, EventArgs e)
        {
            int ret = 0, iMonth = 0;
            string path = "", year = "", month = "";

            if (this.SeletedFilePath == "")
                return;

            this.treeView.Enabled = false;
            this.buttonRead.Enabled = false;
            this.buttonClose.Enabled = false;
            this.checkBoxTypeAlarm.Enabled = false;
            this.checkBoxTypeOperation.Enabled = false;
            this.checkBoxTypeParameter.Enabled = false;

            this.ParentForm.ParentForm.CurrentDataViewerFilter.TypeAlarm = this.checkBoxTypeAlarm.Checked;
            this.ParentForm.ParentForm.CurrentDataViewerFilter.TypeOperation = this.checkBoxTypeOperation.Checked;
            this.ParentForm.ParentForm.CurrentDataViewerFilter.TypeParameter = this.checkBoxTypeParameter.Checked;

            year = this.SeletedFilePath.Substring(1, 4);
            iMonth = int.Parse(this.SeletedFilePath.Substring(5, 2));
            month = iMonth.ToString();
            path = string.Format("{0}{1}\\{2}\\{3}.csv", this.ParentForm.ParentForm.PathDataHistoryFolder, year, month, this.SeletedFilePath);

            ret = this.ParentForm.DataRead(path);
            if (ret == 0)
            {
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            else
                this.DialogResult = DialogResult.Cancel;

            this.treeView.Enabled = true;
            this.buttonRead.Enabled = true;
            this.buttonClose.Enabled = true;
            this.checkBoxTypeAlarm.Enabled = true;
            this.checkBoxTypeOperation.Enabled = true;
            this.checkBoxTypeParameter.Enabled = true;
        }
        private void buttonClose_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            string fileName = "", date = "-";

            if (e.Node.Text.Substring(0, 1) == "H")
            {
                fileName = e.Node.Text;
                date = string.Format("{0}.{1}.{2}", fileName.Substring(1, 4), fileName.Substring(5, 2), fileName.Substring(7, 2));
            }

            this.labelFileName.Text = fileName;
            this.SeletedFilePath = fileName;
            this.labelDate.Text = date;
        }
        #endregion
    }
}