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 INT99DC_7C.Forms;

namespace INT99DC_7C.DialogForms
{
    public partial class DialogFormDataStatistics : Form
    {
        #region Field
        private FormDataStatistics m_ParentForm;
        #endregion
        
        #region Constructor
        public DialogFormDataStatistics(FormDataStatistics parent)
        {
            InitializeComponent();

            this.ParentForm = parent;

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

        #region Property
        public FormDataStatistics 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
            {

            }
        }
        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()
        {
            if (this.ParentForm.ParentForm.SystemConfig.IsPart11 == false)
                this.DisplayTreeViewUpdate1();
            else
                this.DisplayTreeViewUpdate2();

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

        private Collection<List<string>> FileClassification(List<string> files)
        {
            string date = "", date1 = "";
            Collection<List<string>> fileClassification = new Collection<List<string>>();
            List<string> list = new List<string>();

            for (int i = 0; i < files.Count; i++)
            {
                date = files[i].Substring(0, 8);
                if (i == 0)
                    date1 = date;

                if (date == date1)
                {
                    list.Add(files[i]);
                }
                else
                {
                    date1 = date;

                    List<string> l = new List<string>();

                    foreach (string s in list)
                        l.Add(s);

                    fileClassification.Add(l);
                    list = new List<string>();
                    list.Add(files[i]);
                }
            }

            List<string> ls = new List<string>();
            foreach (string s in list)
                ls.Add(s);
            fileClassification.Add(ls);

            return fileClassification;
        }
        private List<string> FileSort(FileInfo[] files)
        {
            List<string> listFiles = new List<string>();
            Dictionary<string, int> fileNames = new Dictionary<string, int>();
            Dictionary<string, int> fileNamesSort = new Dictionary<string, int>();

            foreach (FileInfo file in files)
            {
                if (file.Name.StartsWith("20") == true)
                    fileNames.Add(file.Name, int.Parse(file.Name.Substring(9, 1)));
            }

            var vrList = fileNames.OrderBy(x => x.Value);
            foreach (var v in vrList)
                listFiles.Add(v.Key);

            return listFiles;
        }
        private List<string> FileSort(List<string> lst)
        {
            List<string> listFiles = new List<string>();
            Dictionary<string, int> fileNames = new Dictionary<string, int>();
            Dictionary<string, int> fileNamesSort = new Dictionary<string, int>();

            foreach (string list in lst)
            {
                if (list.Length == 22)
                    fileNames.Add(list, int.Parse(list.Substring(13, 1)));
                else
                    fileNames.Add(list, int.Parse(list.Substring(13, 2)));
            }

            // Lane 순서데로 오름차순 정렬
            var vrList = fileNames.OrderBy(x => x.Value);

            foreach (var v in vrList)
                listFiles.Add(v.Key);

            return listFiles;
        }
        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> DayInspectionDirectorySort(FileInfo[] files)
        {
            List<string> listFile = new List<string>();
            Dictionary<string, int> dirNames = new Dictionary<string, int>();

            #region File List 품번 순서데로 정렬
            foreach (FileInfo file in files)
                dirNames.Add(file.Name, int.Parse(file.Name.Substring(10, 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(1, 8)));

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

            return listFile;
        }

        private void DisplayTreeViewUpdate1()
        {
            int fileCount = 0;

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

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

            FileInfo[] files = dir.GetFiles();

            foreach (FileInfo file in files)
            {
                if (file.Name.StartsWith("20") == true)
                    fileCount++;
            }

            if (fileCount != 0)
            {
                // 파일 이름 순으로 정렬
                fileNames = this.FileSort(files);
                // 파일 날짜 순으로 분류
                this.ParentForm.CollectionFileClassification = this.FileClassification(fileNames);

                foreach (List<string> list in this.ParentForm.CollectionFileClassification)
                {
                    TreeNode node = new TreeNode(list[0].Substring(0, 10));

                    for (int i = 0; i < list.Count; i++)
                    {
                        node.Nodes.Add(list[i]);
                    }

                    this.treeView.Nodes.Add(node);
                }
            }
        }
        private void DisplayTreeViewUpdate2()
        {
            int fileCount = 0;
            //TreeNode node;
            List<DataBackupYear> listInspectionFile = 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();
            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.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.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);
                        }

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

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

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

        public void DisplayRefresh()
        {
        }
        #endregion

        #region Event Handler
        private void buttonRead_Click(object sender, EventArgs e)
        {
            int ret = 0;

            if (this.ParentForm.ParentForm.SystemConfig.IsPart11 == false)
            {
                if (this.ParentForm.SelectNodeIndex == -1)
                    return;

                this.treeView.Enabled = false;
                this.buttonRead.Enabled = false;
                this.buttonClose.Enabled = false;

                if (this.treeView.Nodes.Count != 0)
                {
                    this.ParentForm.ClearData();
                    ret = this.ParentForm.DataRead1();

                    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;
            }
            else
            {
                string selectedFile = "", filePath = "";
                selectedFile = this.GetSeletedNodeList(this.treeView);

                if (selectedFile == "")
                    return;

                this.treeView.Enabled = false;
                this.buttonRead.Enabled = false;
                this.buttonClose.Enabled = false;

                this.ParentForm.ClearData();
                filePath = string.Format("{0}{1}", this.ParentForm.ParentForm.PathDataInspectionFolder, selectedFile);
                ret = this.ParentForm.DataRead1(filePath);

                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;
            }
        }
        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 (this.ParentForm.ParentForm.SystemConfig.IsPart11 == false)
            {
                if (e.Node.Parent == null)
                {
                    fileName = e.Node.Text;
                    this.ParentForm.SelectNodeIndex = e.Node.Index;
                    //this.labelNodeIndex.Text = string.Format("{0}", this.ParentForm.SelectNodeIndex + 1);
                }
                else
                {
                    fileName = e.Node.Parent.Text;
                    this.ParentForm.SelectNodeIndex = e.Node.Parent.Index;
                    //this.labelNodeIndex.Text = string.Format("{0}", this.ParentForm.SelectNodeIndex + 1);
                }

                date = string.Format("{0}.{1}.{2}", fileName.Substring(0, 4), fileName.Substring(4, 2), fileName.Substring(6, 2));
            }
            else
            {
                if (e.Node.Text.Substring(0, 1) == "I")
                {
                    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.labelDate.Text = date;
        }
        #endregion

        private string GetSeletedNodeList(TreeView tree)
        {
            int yearCNT, monthCNT, dayCNT;
            List<string> listSelectedFile = new List<string>();
            string selectedFile = "";

            yearCNT = tree.Nodes.Count;
            if (yearCNT != 0)
            {
                for (int i = 0; i < yearCNT; i++)
                {
                    monthCNT = tree.Nodes[i].Nodes.Count;
                    if (monthCNT != 0)
                    {
                        for (int j = 0; j < monthCNT; j++)
                        {
                            dayCNT = tree.Nodes[i].Nodes[j].Nodes.Count;
                            if (dayCNT != 0)
                            {
                                for (int k = 0; k < dayCNT; k++)
                                {
                                    if (tree.Nodes[i].Nodes[j].Nodes[k].IsSelected == true)
                                    {
                                        //listSelectedFile.Add(tree.Nodes[i].Nodes[j].Nodes[k].Text);
                                        //listSelectedFile.Add(string.Format("{0}\\{1}\\{2}", tree.Nodes[i].Text, tree.Nodes[i].Nodes[j].Text, tree.Nodes[i].Nodes[j].Nodes[k].Text));
                                        selectedFile = string.Format("{0}\\{1}\\{2}", tree.Nodes[i].Text, tree.Nodes[i].Nodes[j].Text, tree.Nodes[i].Nodes[j].Nodes[k].Text);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return selectedFile;
        }
    }
}