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

using SmartX;
using INT63DC_ImageDll;
using INT63DC_2C.DialogForms;
using INT63DC_2C.Part11_Encryption;

namespace INT63DC_2C.Forms
{
    public partial class FormDataBackup_Part11 : Form
    {
        #region Field
        private FormMain m_ParentForm;
        private SmartSplash Splash;
        private string EncFileName;
        private DataStore.E_DataType SelecteDataType;
        private int CopyFileCount;

        private List<DataBackupYear> ListInspectionFile;
        private List<DataBackupYear> ListHistoryFile;

        private Queue<string> Q_FileList = new Queue<string>();
        #endregion

        #region Constructor
        public FormDataBackup_Part11(FormMain parent)
        {
            InitializeComponent();

            this.ParentForm = parent;

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

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

        #region Method
        private void InitializeDesign()
        {
            ImageDll images = new ImageDll();

            if (this.ParentForm.SystemConfig.Language == DataStore.E_LanguageID.Korean)
            {

            }
            else if (this.ParentForm.SystemConfig.Language == DataStore.E_LanguageID.English)
            {
                this.labelTitle.Text = "Data backup";

                this.buttonBack.DisableImage = new Bitmap(images.GetImage(ImageDll.ButtonImages.engBackDisable));
                this.buttonBack.DownImage = new Bitmap(images.GetImage(ImageDll.ButtonImages.engBackDown));
                this.buttonBack.UpImage = new Bitmap(images.GetImage(ImageDll.ButtonImages.engBackUp));
            }
            else if (this.ParentForm.SystemConfig.Language == DataStore.E_LanguageID.Chinese)
            {
                this.labelTitle.Text = "数据备份";

                this.buttonBack.DisableImage = new Bitmap(images.GetImage(ImageDll.ButtonImages.chnBackDisable));
                this.buttonBack.DownImage = new Bitmap(images.GetImage(ImageDll.ButtonImages.chnBackDown));
                this.buttonBack.UpImage = new Bitmap(images.GetImage(ImageDll.ButtonImages.chnBackUp));
            }
            else if (this.ParentForm.SystemConfig.Language == DataStore.E_LanguageID.Czech)
            {
                this.labelTitle.Text = "Záloha dat";

                this.buttonBack.DisableImage = new Bitmap(images.GetImage(ImageDll.ButtonImages.czeBackDisable));
                this.buttonBack.DownImage = new Bitmap(images.GetImage(ImageDll.ButtonImages.czeBackDown));
                this.buttonBack.UpImage = new Bitmap(images.GetImage(ImageDll.ButtonImages.czeBackUp));
            }
            else if (this.ParentForm.SystemConfig.Language == DataStore.E_LanguageID.German)
            {
                this.labelTitle.Text = "Datensicherung";

                this.buttonBack.DisableImage = new Bitmap(images.GetImage(ImageDll.ButtonImages.gerBackDisable));
                this.buttonBack.DownImage = new Bitmap(images.GetImage(ImageDll.ButtonImages.gerBackDown));
                this.buttonBack.UpImage = new Bitmap(images.GetImage(ImageDll.ButtonImages.gerBackUp));
            }
            else
            {

            }
        }
        private void DefaultSetting()
        {
            this.EncFileName = "";
            this.SelecteDataType = DataStore.E_DataType.None;
            this.CopyFileCount = 0;

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

        // Backup
        private void Backup(DataStore.E_DataType type, TreeView view)
        {
            string targetPath = "", sourceFilePath = "", destFilePath = "", dataFolderPath = "";
            string[] result;
            DirectoryInfo dir;
            FileInfo[] files;
            List<string> listSelectedFile = new List<string>();     // 백업할 파일 리스트 (yyyy/MM/filename.csv)
            this.Q_FileList = new Queue<string>();

            switch (type)
            {
                case DataStore.E_DataType.None:
                    break;
                case DataStore.E_DataType.History:
                    dataFolderPath = this.ParentForm.PathDataHistoryFolder;
                    break;
                case DataStore.E_DataType.Inspection:
                    dataFolderPath = this.ParentForm.PathDataInspectionFolder;
                    break;
                default:
                    break;
            }

            if (dataFolderPath == "")
                return;

            targetPath = "하드 디스크\\";
            
            #region 백업 할 파일 리스트
            listSelectedFile = this.GetSeletedNodeList(view);
            this.CopyFileCount = listSelectedFile.Count;
            #endregion

            #region 백업할 파일 유무 체크
            if (listSelectedFile.Count == 0)
            {
                DialogFormMessage msg = new DialogFormMessage(4, this.ParentForm.SystemConfig.Language);
                msg.ShowDialog();
                return;
            }
            #endregion

            #region USB 장착 유무 체크
            dir = new DirectoryInfo(targetPath);
            if (dir.Exists == false)
            {
                // USB메모리가 장착되지 않았습니다
                DialogFormMessage msg = new DialogFormMessage(5, this.ParentForm.SystemConfig.Language);
                msg.ShowDialog();
                return;
            }
            #endregion

            // Splash Start
            this.SplashStart();

            #region Header && Encryption 폴더에 파일 삭제
            this.DirectoryFileDelete(this.ParentForm.PathEncryptionFolder);
            this.DirectoryFileDelete(this.ParentForm.PathHeaderFolder);
            #endregion

            try
            {
                #region Header 파일 생성
                // Header 파일 생성
                FileHeaderItem header = new FileHeaderItem();
                header.TimeStamp = DateTime.Now;
                header.LoginId = this.ParentForm.SystemConfig.CurrentUser.ID;
                header.SerialNumber = this.ParentForm.SystemConfig.SerialNumber;
                header.EquipmentColumns = this.ParentForm.SystemConfig.EquipmentColumns;
                header.EquipmentType = 105;

                for (int i = 0; i < listSelectedFile.Count; i++)
                    this.CreateHeaderFile(this.ParentForm.PathHeaderFolder, listSelectedFile[i], header);
                #endregion

                #region 파일 암호화
                // 데이터 파일
                for (int i = 0; i < listSelectedFile.Count; i++)
                    this.Q_FileList.Enqueue(string.Format("{0}{1}", dataFolderPath, listSelectedFile[i]));
                // 헤더 파일
                dir = new DirectoryInfo(this.ParentForm.PathHeaderFolder);
                files = dir.GetFiles();
                foreach (FileInfo file in files)
                {
                    result = file.FullName.Split('\\');
                    sourceFilePath = file.FullName;
                    destFilePath = string.Format("{0}{1}", this.ParentForm.PathEncryptionFolder, result[result.Length - 1]);

                    this.Q_FileList.Enqueue(file.FullName);
                }

                this.EncryptionFile(this.Q_FileList.Dequeue());
                #endregion
            }
            catch
            {
                // 제조사에 문의하세요
                DialogFormMessage msg = new DialogFormMessage(6, this.ParentForm.SystemConfig.Language);
                this.SplashFinish();
                msg.ShowDialog();
                return;
            }
        }
        // FileCopy
        private void FileCopy(DataStore.E_DataType type)
        {
            int count = 0;
            string targetPath = "", destTargetPath = "", sourceFilePath = "", destFilePath = "";
            string[] result;
            DirectoryInfo dir;
            FileInfo[] files;

            try
            {
                #region USB 복사
                targetPath = "하드 디스크\\";

                // USB\SerialNumber\ 루트
                destTargetPath = string.Format("{0}{1}\\Data\\{2}\\{3}\\", targetPath, this.ParentForm.SystemConfig.SerialNumber, type, DateTime.Now.ToString("yyyyMMdd_HHmmss"));

                // USB 폴더 체크 및 생성
                dir = new DirectoryInfo(destTargetPath);
                if (dir.Exists == false)
                    dir.Create();

                // 파일 복사
                dir = new DirectoryInfo(this.ParentForm.PathEncryptionFolder);
                if (dir.Exists == false)
                    dir.Create();

                files = dir.GetFiles();
                count = files.Length;
                foreach (FileInfo file in files)
                {
                    result = file.FullName.Split('\\');
                    sourceFilePath = file.FullName;
                    destFilePath = string.Format("{0}{1}", destTargetPath, result[result.Length - 1]);

                    // 파일 중복 검사
                    if (File.Exists(destFilePath) == true)
                    {
                        DialogFormYesNo df = new DialogFormYesNo(this.ParentForm.SystemConfig.Language, 31, Path.GetFileName(result[result.Length - 1]));
                        df.BringToFront();
                        if (df.ShowDialog() == DialogResult.Yes)
                        {
                            this.Refresh();
                            File.Delete(destFilePath);  // 존재하는 파일 삭제
                            File.Copy(sourceFilePath, destFilePath);
                        }
                        else
                        {
                            count--;
                            this.Refresh();
                        }
                    }
                    else
                    {
                        File.Copy(sourceFilePath, destFilePath);
                    }
                }

                if (type == DataStore.E_DataType.Others)
                {
                    dir = new DirectoryInfo(this.ParentForm.PathDataBackupFolder);
                    files = dir.GetFiles();
                    foreach (FileInfo file in files)
                        file.Delete();

                    this.UpdateDisplayOtherFile();
                }

                // 복사 완료 메시지
                DialogFormMessage msg = new DialogFormMessage(this.CopyFileCount.ToString(), this.ParentForm.SystemConfig.Language, type.ToString());
                this.ParentForm.SetTrackingHistoryData(DataStore.E_TrackingOperation.DataBackup, type.ToString());
                this.SplashFinish();
                msg.ShowDialog();
                #endregion
            }
            catch
            {
                // 제조사에 문의하세요
                DialogFormMessage msg = new DialogFormMessage(6, this.ParentForm.SystemConfig.Language);
                this.SplashFinish();
                msg.ShowDialog();
                return;
            }
        }
        // OtherBackup
        private void OtherBackup()
        {
            string targetPath = "", sourceFilePath = "", destFilePath = "", dataFolderPath = "";
            string[] result;
            DirectoryInfo dir;
            FileInfo[] files;
            this.Q_FileList = new Queue<string>();

            dataFolderPath = this.ParentForm.PathDataBackupFolder;

            if (dataFolderPath == "")
                return;

            targetPath = "하드 디스크\\";

            #region 백업할 파일 유무 체크
            if (this.listBoxOther.Items.Count == 0)
            {
                DialogFormMessage msg = new DialogFormMessage(4, this.ParentForm.SystemConfig.Language);
                msg.ShowDialog();
                return;
            }
            #endregion

            #region USB 장착 유무 체크
            // USB 장착 유무 체크
            dir = new DirectoryInfo(targetPath);
            if (dir.Exists == false)
            {
                // USB메모리가 장착되지 않았습니다
                DialogFormMessage msg = new DialogFormMessage(5, this.ParentForm.SystemConfig.Language);
                msg.ShowDialog();
                return;
            }
            #endregion

            this.SplashStart();

            #region Header && Encryption 폴더에 파일 삭제
            this.DirectoryFileDelete(this.ParentForm.PathEncryptionFolder);
            this.DirectoryFileDelete(this.ParentForm.PathHeaderFolder);
            #endregion

            try
            {
                dir = new DirectoryInfo(this.ParentForm.PathDataBackupFolder);
                files = dir.GetFiles();
                this.CopyFileCount = files.Length;
                List<string> listSelectedFile = new List<string>();

                // jpg 파일 -> EncryptionFolder로 복사
                foreach (FileInfo file in files)
                {
                    if (file.Name.Substring(file.Name.Length - 3, 3) == "jpg")
                    {
                        file.CopyTo(string.Format("{0}{1}", this.ParentForm.PathEncryptionFolder, file.Name));
                        file.Delete();
                    }
                    else
                        listSelectedFile.Add(file.FullName);
                }

                #region Header 파일 생성
                // Header 파일 생성
                FileHeaderItem header = new FileHeaderItem();
                header.TimeStamp = DateTime.Now;
                header.LoginId = this.ParentForm.SystemConfig.CurrentUser.ID;
                header.SerialNumber = this.ParentForm.SystemConfig.SerialNumber;
                header.EquipmentColumns = this.ParentForm.SystemConfig.EquipmentColumns;
                header.EquipmentType = 105;

                for (int i = 0; i < listSelectedFile.Count; i++)
                    this.CreateHeaderFile(this.ParentForm.PathHeaderFolder, listSelectedFile[i], header);
                #endregion

                #region 파일 암호화
                // 데이터 파일
                for (int i = 0; i < listSelectedFile.Count; i++)
                    this.Q_FileList.Enqueue(listSelectedFile[i]);
                // 헤더 파일
                dir = new DirectoryInfo(this.ParentForm.PathHeaderFolder);
                files = dir.GetFiles();
                foreach (FileInfo file in files)
                {
                    result = file.FullName.Split('\\');
                    sourceFilePath = file.FullName;
                    destFilePath = string.Format("{0}{1}", this.ParentForm.PathEncryptionFolder, result[result.Length - 1]);

                    this.Q_FileList.Enqueue(file.FullName);
                }

                this.EncryptionFile(this.Q_FileList.Dequeue());
                #endregion
            }
            catch
            {
                // 제조사에 문의하세요
                DialogFormMessage msg = new DialogFormMessage(6, this.ParentForm.SystemConfig.Language);
                this.SplashFinish();
                msg.ShowDialog();
                return;
            }

            this.UpdateDisplayOtherFile();
        }

        private void SplashStart()
        {
            this.Splash = new SmartX.SmartSplash();
            this.Splash.CenterPosition = false;
            this.Splash.Left = 480;
            this.Splash.Top = 360;
            this.Splash.AnimationInterval = 200;
            this.Splash.LoadingImagePathname = "SmartLoading4";
            this.Splash.Start();
            this.Enabled = false;
        }
        private void SplashFinish()
        {
            this.Splash.Finish();
            this.Enabled = true;

            this.EncFileName = "";
            this.labelFileName.Text = "-";
            this.labelPercentage.Text = "0%";
            this.SelecteDataType = DataStore.E_DataType.None;
        }

        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>();
            string[] fileName;

            #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;
        }
        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 List<string> GetSeletedNodeList(TreeView tree)
        {
            int yearCNT, monthCNT, dayCNT;
            List<string> listSelectedFile = new List<string>();

            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].Checked == true)
                                    {
                                        //listSelectedFile.Add(tree.Nodes[i].Nodes[j].Nodes[k].Text);
                                        listSelectedFile.Add(string.Format("{0}\\{1}\\{2}.csv", tree.Nodes[i].Text, tree.Nodes[i].Nodes[j].Text, tree.Nodes[i].Nodes[j].Nodes[k].Text));
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return listSelectedFile;
        }

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

            this.labelInspectionFileCount.Text = fileCount.ToString();
        }
        private void UpdateDisplayHistoryFile()
        {
            int fileCount = 0;
            string[] fileName;
            List<string> years = new List<string>();
            List<string> months = new List<string>();
            List<string> days = new List<string>();

            this.treeViewHistory.Nodes.Clear();
            this.ListHistoryFile.Clear();

            DirectoryInfo dir = new DirectoryInfo(this.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.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.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++)
                        {
                            fileName = this.ListHistoryFile[i].Months[j].Days[k].Split('.');
                            nodeMonth.Nodes.Add(fileName[0]);
                            fileCount++;
                        }
                        node.Nodes.Add(nodeMonth);
                    }
                    this.treeViewHistory.Nodes.Add(node);
                }
            }
            this.labelHistoryFileCount.Text = fileCount.ToString();
        }
        private void UpdateDisplayOtherFile()
        {
            bool directoryCheck = false;
            string[] fileName;

            this.ParentForm.SystemConfig.CurrentForm = DataStore.FormStore.FormDataBackup;

            DirectoryInfo dir = new DirectoryInfo(this.ParentForm.PathDataBackupFolder);

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

            FileInfo[] files = dir.GetFiles();

            this.listBoxOther.Items.Clear();

            foreach (FileInfo file in files)
            {
                if (file.Name.Substring(0, 1) == "S")
                {
                    fileName = file.Name.Split('.');
                    this.listBoxOther.Items.Add(fileName[0]);
                }
                else
                    this.listBoxOther.Items.Add(file.Name);
            }

            this.labelOtherFileCount.Text = this.listBoxOther.Items.Count.ToString();
        }

        private void EncryptionFile(string sourceFilePath)
        {
            string[] data = sourceFilePath.Split('\\');
            string destinationFilePath = string.Format("{0}{1}", this.ParentForm.PathEncryptionFolder, data[data.Length - 1]);

            this.UI_Invoke(delegate
            {
                this.labelFileName.Text = data[data.Length - 1];
                this.EncFileName = sourceFilePath;
            });

            Encryption.AesEncryption(sourceFilePath, destinationFilePath, true, true);
        }

        public void EnableBackupButton(bool enable)
        {
            this.buttonInspectionBackup.Enabled = enable;
            this.buttonHistoryBackup.Enabled = enable;
            this.buttonOtherBackup.Enabled = enable;
        }

        private void CreateHeaderFile(string headerFilePath, string sourceFilePath, FileHeaderItem header)
        {
            string[] result, fileName;
            string filePath, section, key, value;

            result = sourceFilePath.Split('\\');
            fileName = result[result.Length - 1].Split('.');
            filePath = string.Format("{0}{1}_h.ini", headerFilePath, fileName[0]);
            section = header.GetType().Name;

            // LoginID
            key = DataStore.E_FileHeaderItem.LoginId.ToString();
            value = header.LoginId;
            IniFile.WriteString(filePath, section, key, value);
            Thread.Sleep(5);

            // SerialNumber
            key = DataStore.E_FileHeaderItem.SerialNumber.ToString();
            value = header.SerialNumber;
            IniFile.WriteString(filePath, section, key, value);
            Thread.Sleep(5);

            // EquipmentColumns
            key = DataStore.E_FileHeaderItem.EquipmentColumns.ToString();
            value = header.EquipmentColumns.ToString();
            IniFile.WriteString(filePath, section, key, value);
            Thread.Sleep(5);

            // TimeStamp
            key = DataStore.E_FileHeaderItem.TimeStamp.ToString();
            value = header.TimeStamp.ToString("MM/dd/yyyy HH:mm:ss");
            IniFile.WriteString(filePath, section, key, value);
            Thread.Sleep(5);

            // EquipmentType
            key = DataStore.E_FileHeaderItem.EquipmentType.ToString();
            value = header.EquipmentType.ToString();
            IniFile.WriteString(filePath, section, key, value);
            Thread.Sleep(5);
        }
        private void DirectoryFileDelete(string dirPath)
        {
            DirectoryInfo dir = new DirectoryInfo(dirPath);
            FileInfo[] files = dir.GetFiles();

            foreach (FileInfo file in files)
            {
                file.Delete();
            }
        }
        private bool UI_Invoke(ThreadStart invoker)
        {
            try
            {
                if (this.InvokeRequired)
                {
                    if (this.IsDisposed)
                        return true;

                    this.Invoke(invoker);
                }
                else
                {
                    invoker();
                }

                return true;

            }
            catch (Exception e)
            {
                return false;
            }

        }

        public void CallBackEncryptionEvent(Encryption.auth_encryption_status_t sender)
        {
            if (sender.inFileName == this.EncFileName)
            {
                this.UI_Invoke(delegate
                {
                    this.labelPercentage.Text = string.Format("{0} %", sender.percentage);
                });

                if (sender.percentage == 100)
                {
                    if (sender.status == 0)
                    {
                        if (this.Q_FileList.Count != 0)
                        {
                            this.UI_Invoke(delegate
                            {
                                this.timerEncryption.Enabled = true;
                            });

                        }
                        else
                        {
                            this.UI_Invoke(delegate
                            {
                                this.timerFileCopy.Enabled = true;
                            });
                        }
                    }
                }
            }
        }

        public void DisplayRefresh()
        {
            this.ParentForm.SystemConfig.CurrentForm = DataStore.FormStore.FormDataBackup;

            this.EncFileName = "";
            this.labelFileName.Text = "-";
            this.labelPercentage.Text = "0%";
            this.SelecteDataType = DataStore.E_DataType.None;

            this.UpdateDisplayInspectionFile();
            this.UpdateDisplayHistoryFile();
            this.UpdateDisplayOtherFile();

            //this.treeViewInspection.ExpandAll();
            //this.treeViewHistory.ExpandAll();
        }
        #endregion

        #region Event Handler
        private void buttonBack_Click(object sender, EventArgs e)
        {
            ((FormMain)(Owner)).smartForm.Show(2);
        }

        private void treeViewInspection_AfterSelect(object sender, TreeViewEventArgs e)
        {
            //if (e.Node.Text.Substring(0, 1) == "I")
            //{
            //    if (e.Node.Checked == true)
            //        e.Node.Checked = false;
            //    else
            //        e.Node.Checked = true;
            //}
        }
        private void treeViewHistory_AfterSelect(object sender, TreeViewEventArgs e)
        {
            //if (e.Node.Text.Substring(0, 1) == "H")
            //{
            //    if (e.Node.Checked == true)
            //        e.Node.Checked = false;
            //    else
            //        e.Node.Checked = true;
            //}
        }

        private void buttonInspectionBackupEncryption_Click(object sender, EventArgs e)
        {
            this.SelecteDataType = DataStore.E_DataType.Inspection;
            this.Backup(this.SelecteDataType, this.treeViewInspection);
        }
        private void buttonHistoryBackupEncryption_Click(object sender, EventArgs e)
        {
            this.SelecteDataType = DataStore.E_DataType.History;
            this.Backup(this.SelecteDataType, this.treeViewHistory);
        }
        private void buttonOtherBackup_Click(object sender, EventArgs e)
        {
            this.SelecteDataType = DataStore.E_DataType.Others;
            this.OtherBackup();
        }

        private void timerEncryption_Tick(object sender, EventArgs e)
        {
            this.timerEncryption.Enabled = false;
            this.EncryptionFile(this.Q_FileList.Dequeue());
        }
        private void timerFileCopy_Tick(object sender, EventArgs e)
        {
            this.timerFileCopy.Enabled = false;
            this.FileCopy(this.SelecteDataType);
        }
        #endregion
    }
}