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 DialogFormDataStatistics : Form
    {
        #region Field
        private FormDataStatistics m_ParentForm;

        public List<string> ListFiles;                  // 파일 리스트 - Part11 미사용 시
        public List<DataBackupYear> ListInspectionFile; // 파일 리스트 - Part11 사용 시
        #endregion
        
        #region Constructor
        public DialogFormDataStatistics(FormDataStatistics parent)
        {
            InitializeComponent();

            this.ParentForm = parent;

            this.InitializeDesign();
            this.InitializeControl();
            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()
        { 
        }
        private void InitializeControl()
        {
            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.ListFiles = new List<string>();
            this.ListInspectionFile = new List<DataBackupYear>();

            if (this.ParentForm.ParentForm.SystemConfig.IsOptPart11 == false)
                this.DisplayTreeViewUpdate1();
            else
                this.DisplayTreeViewUpdate2();

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

        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)
        {
            string[] fileName;
            List<string> listFile = new List<string>();
            Dictionary<string, int> dirNames = new Dictionary<string, int>();

            #region File List 품번 순서데로 정렬
            foreach (FileInfo file in files)
            {
                fileName = file.Name.Split('-');
                dirNames.Add(file.Name, int.Parse(fileName[1].Substring(0, fileName[1].Length - 4)));
            }

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

            #region File List 품번 순서데로 정렬
            foreach (FileInfo file in files)
            {
                fileName = file.Name.Split('-');
                dirNames.Add(file.Name, int.Parse(fileName[1].Substring(0, fileName[1].Length - 4)));
            }

            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;
        }

        /// <summary>
        /// Part11 미사용
        /// </summary>
        private void DisplayTreeViewUpdate1()
        {
            DirectoryInfo dir = new DirectoryInfo(this.ParentForm.ParentForm.PathDataBackupFolder);
            List<string> fileNames = new List<string>();

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

            FileInfo[] files = dir.GetFiles();

            if (files.Length != 0)
            {
                // 날짜, 품번 순으로 정렬
                fileNames = this.DayInspectionDirectorySort(files);
                this.ListFiles = fileNames;

                foreach (string name in fileNames)
                {
                    this.treeView1.Nodes.Add(name);
                }
            }
        }
        /// <summary>
        /// Part11 사용
        /// </summary>
        private void DisplayTreeViewUpdate2()
        {
            int fileCount = 0;
            string[] fileName;
            //TreeNode node;
            List<string> years = new List<string>();
            List<string> months = new List<string>();
            List<string> days = new List<string>();

            this.treeView1.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.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.DayInspectionDirectorySort2(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++)
                        {
                            fileName = this.ListInspectionFile[i].Months[j].Days[k].Split('.');
                            nodeMonth.Nodes.Add(fileName[0]);
                            fileCount++;
                        }
                        node.Nodes.Add(nodeMonth);
                    }
                    this.treeView1.Nodes.Add(node);
                }
            }

            //this.labelInspectionFileCount.Text = fileCount.ToString();
        }

        public void DisplayRefresh()
        {
            if (this.ParentForm.ParentForm.SystemConfig.IsOptPart11 == false)
                this.DisplayTreeViewUpdate1();
            else
                this.DisplayTreeViewUpdate2();
        }
        #endregion

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

            if (this.ParentForm.SelectFilePath == "")
                return;

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

            this.ParentForm.ClearData();
            ret = this.ParentForm.DataRead();

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

            this.treeView1.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 = "", pathFileName = "";
            string[] name;

            if (this.ParentForm.ParentForm.SystemConfig.IsOptPart11 == false)
            {
                //fileName = e.Node.Text;
                fileName = e.Node.Text.Substring(0, e.Node.Text.Length - 4);
             
                this.ParentForm.SelectFilePath = string.Format("{0}{1}.csv", this.ParentForm.ParentForm.PathDataBackupFolder, fileName);
                name = fileName.Split('-');
                this.labelFileName.Text = fileName;
                this.labelDate.Text = string.Format("{0}.{1}.{2}", name[0].Substring(0, 4), name[0].Substring(4, 2), name[0].Substring(6, 2));
                this.labelProductNo.Text = name[1];
            }
            else
            {
                if (e.Node.Text.Length > 10)
                {
                    fileName = e.Node.Text;
                    pathFileName = string.Format("{0}{1}\\{2}\\{3}.csv",
                        this.ParentForm.ParentForm.PathDataInspectionFolder, fileName.Substring(1, 4), int.Parse(fileName.Substring(5, 2)), fileName);
                    this.ParentForm.SelectFilePath = pathFileName;

                    name = fileName.Split('-');
                    this.labelFileName.Text = fileName;
                    this.labelDate.Text = string.Format("{0}.{1}.{2}", name[0].Substring(1, 4), name[0].Substring(5, 2), name[0].Substring(7, 2));
                    this.labelProductNo.Text = name[1];
                }
            }
        }
        #endregion
    }
}