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

using ITC81DB.Forms;
using ITC81DB.DialogForms;
using ITC81DB_ImageDll;

namespace ITC81DB.Controls
{
    public partial class ControlCenterEquipInitialize : UserControl
    {
        #region Field
        private FormMenu m_ParentForm;
        private DataStore.Step3 InitializeStep;

        private int FlagTimeout;
        #endregion

        #region Constructor
        public ControlCenterEquipInitialize(FormMenu parent)
        {
            InitializeComponent();

            this.ParentForm = parent;

            this.InitializeDesign();
        }
        #endregion

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

        #region Method
        public void InitializeDesign()
        {
            Class1 images = new Class1();

            if (this.ParentForm.ParentForm.SystemConfig1.Language == DataStore.LanguageID.English)
            {
                this.buttonBackup.Font = this.buttonMainBoardLcd.Font = this.buttonLcd.Font = new Font("새굴림", 18, FontStyle.Bold);
                this.buttonMainBoard.Font = this.buttonSystemInitialization.Font = new Font("새굴림", 18, FontStyle.Bold);

                this.buttonBackup.Text = "Backup";
                this.buttonMainBoardLcd.Text = "Mainboard+LCD";
                this.buttonMainBoard.Text = "Mainboard";
                this.buttonLcd.Text = "LCD";
                this.buttonSystemInitialization.Text = "System Init";
            }
            else if (this.ParentForm.ParentForm.SystemConfig1.Language == DataStore.LanguageID.Chinese)
            {
                this.buttonBackup.Font = this.buttonMainBoardLcd.Font = this.buttonLcd.Font = new Font("새굴림", 18, FontStyle.Bold);
                this.buttonMainBoard.Font = this.buttonSystemInitialization.Font = new Font("새굴림", 18, FontStyle.Bold);

                this.buttonBackup.Text = "备份";
                this.buttonMainBoardLcd.Text = "主板+LCD";
                this.buttonMainBoard.Text = "主板";
                this.buttonLcd.Text = "LCD";
                this.buttonSystemInitialization.Text = "所有初始化";
            }
            else if (this.ParentForm.ParentForm.SystemConfig1.Language == DataStore.LanguageID.Czech)
            {
            }
            else if (this.ParentForm.ParentForm.SystemConfig1.Language == DataStore.LanguageID.Russian)
            {
                this.buttonBackup.Font = this.buttonMainBoardLcd.Font = this.buttonLcd.Font = new Font("새굴림", 13, FontStyle.Bold);
                this.buttonMainBoard.Font = this.buttonSystemInitialization.Font = new Font("새굴림", 13, FontStyle.Bold);

                this.buttonBackup.Text = "Возврат";
                this.buttonMainBoardLcd.Text = "главной платы+LCD";
                this.buttonMainBoard.Text = "главной платы";
                this.buttonLcd.Text = "LCD";
                this.buttonSystemInitialization.Text = "Системы";
            }
            else if (this.ParentForm.ParentForm.SystemConfig1.Language == DataStore.LanguageID.German)
            {
                this.buttonBackup.Font = this.buttonMainBoardLcd.Font = this.buttonLcd.Font = new Font("새굴림", 18, FontStyle.Bold);
                this.buttonMainBoard.Font = this.buttonSystemInitialization.Font = new Font("새굴림", 18, FontStyle.Bold);

                this.buttonBackup.Text = "Sicherung";
                this.buttonMainBoardLcd.Text = "Mainboard+LCD";
                this.buttonMainBoard.Text = "Mainboard";
                this.buttonLcd.Text = "LCD";
                this.buttonSystemInitialization.Text = "System";
            }
            else if (this.ParentForm.ParentForm.SystemConfig1.Language == DataStore.LanguageID.Spanish)
            {
                this.buttonBackup.Font = this.buttonMainBoardLcd.Font = this.buttonLcd.Font = new Font("새굴림", 18, FontStyle.Bold);
                this.buttonMainBoard.Font = this.buttonSystemInitialization.Font = new Font("새굴림", 18, FontStyle.Bold);

                this.buttonBackup.Text = "Respaldo";
                this.buttonMainBoardLcd.Text = "Placa base+LCD";
                this.buttonMainBoard.Text = "Placa base";
                this.buttonLcd.Text = "LCD";
                this.buttonSystemInitialization.Text = "Inicializar";
            }
            else
            {
                this.buttonBackup.Font = this.buttonMainBoardLcd.Font = this.buttonLcd.Font = new Font("새굴림", 18, FontStyle.Bold);
                this.buttonMainBoard.Font = this.buttonSystemInitialization.Font = new Font("새굴림", 18, FontStyle.Bold);

                this.buttonBackup.Text = "Backup";
                this.buttonMainBoardLcd.Text = "Mainboard+LCD";
                this.buttonMainBoard.Text = "Mainboard";
                this.buttonLcd.Text = "LCD";
                this.buttonSystemInitialization.Text = "System Init";
            }
        }
        private void DefaultSetting()
        {
            this.FlagTimeout = 0;
            this.timer.Interval = 500;

            this.progressBarInitialize.Value = 0;

            this.InitializeStep = DataStore.Step3.Step1;
            this.UpdateLabelStatus(this.InitializeStep, this.ParentForm.ParentForm.SystemConfig1.Language);
        }

        private void DeleteFolder(string address)
        {
            DirectoryInfo dir = new DirectoryInfo(address);
            if (dir.Exists == true)
                dir.Delete(true);
        }
        private void CopyFolder(string departure, string destination)
        {
            DirectoryInfo dirDestination = new DirectoryInfo(destination);
            if (dirDestination.Exists == false)
                dirDestination.Create();

            FileInfo[] files;

            DirectoryInfo dirDeparture = new DirectoryInfo(departure);
            if (dirDeparture.Exists == true)
            {
                files = dirDeparture.GetFiles();
                foreach (FileInfo subFile in files)
                    subFile.CopyTo(destination + subFile.Name, true);
            }
        }
        private void MoveToRemoveFileFolder(string address)
        {

            DirectoryInfo dirDestination = new DirectoryInfo(this.ParentForm.ParentForm.PathSDCardRemoveFileFolder);
            if (dirDestination.Exists == false)
                dirDestination.Create();

            FileInfo[] files;

            DirectoryInfo dirDeparture = new DirectoryInfo(address);
            if (dirDeparture.Exists == true)
            {
                files = dirDeparture.GetFiles();
                foreach (FileInfo subFile in files)
                    subFile.MoveTo(this.ParentForm.ParentForm.PathSDCardRemoveFileFolder + string.Format("{0:yyyyMMddHHmmss}", DateTime.Now) + subFile.Name);
            }
        }

        private void InitializeMainBoard(DialogResult result)
        {
            if (result == DialogResult.Yes)
            {
                this.timer.Enabled = true;
                this.progressBarInitialize.Value = 0;

                this.InitializeStep = DataStore.Step3.Step2;
                this.UpdateLabelStatus(this.InitializeStep, this.ParentForm.ParentForm.SystemConfig1.Language);

                this.ParentForm.ParentForm.TransferData(CommunicationCommand.Initialization, CommunicationID.MainBoard);
            }
        }
        private void InitializeLcd(DialogResult result)
        {
            if (result == DialogResult.Yes)
            {
                this.InitializeStep = DataStore.Step3.Step2;
                this.UpdateLabelStatus(this.InitializeStep, this.ParentForm.ParentForm.SystemConfig1.Language);

                this.progressBarInitialize.Value = 0;
                this.progressBarInitialize.Value += 20;
                // SD Card - SystemFile2를 RemoveFiles로 이동
                this.MoveToRemoveFileFolder(this.ParentForm.ParentForm.PathSDCardSystemFile2Folder);
                this.progressBarInitialize.Value += 20;
                // Flash Disk - SystemFile2 이동
                this.CopyFolder(this.ParentForm.ParentForm.PathFlashDiskSystemFile2Folder, this.ParentForm.ParentForm.PathSDCardSystemFile2Folder);
                this.progressBarInitialize.Value += 20;
                this.InitializeCount(this.ParentForm.ParentForm.SystemConfig1.ProductNumber);
                this.progressBarInitialize.Value = 100;

                this.InitializeStep = DataStore.Step3.Step3;
                this.UpdateLabelStatus(this.InitializeStep, this.ParentForm.ParentForm.SystemConfig1.Language);

                this.ParentForm.Enabled = false;
            }
        }
        private void InitializeMainBoardLcd(DialogResult result)
        {
            if (result == DialogResult.Yes)
            {
                this.InitializeStep = DataStore.Step3.Step2;
                this.UpdateLabelStatus(this.InitializeStep, this.ParentForm.ParentForm.SystemConfig1.Language);

                this.progressBarInitialize.Value = 0;
                this.progressBarInitialize.Value += 15;
                // SD Card - SystemFile2를 RemoveFiles로 이동
                this.MoveToRemoveFileFolder(this.ParentForm.ParentForm.PathSDCardSystemFile2Folder);
                this.progressBarInitialize.Value += 15;
                // Flash Disk - SystemFile2 이동
                this.CopyFolder(this.ParentForm.ParentForm.PathFlashDiskSystemFile2Folder, this.ParentForm.ParentForm.PathSDCardSystemFile2Folder);
                this.progressBarInitialize.Value += 15;
                this.InitializeCount(this.ParentForm.ParentForm.SystemConfig1.ProductNumber);
                this.progressBarInitialize.Value += 15;

                this.timer.Enabled = true;
                this.ParentForm.ParentForm.TransferData(CommunicationCommand.Initialization, CommunicationID.MainBoard);
            }
        }
        private void BackupSystemFile(DialogResult result)
        {
            if (result == DialogResult.Yes)
            {
                this.InitializeStep = DataStore.Step3.Step2;
                this.UpdateLabelStatus(this.InitializeStep, this.ParentForm.ParentForm.SystemConfig1.Language);

                this.progressBarInitialize.Value = 0;
                // Flash Disk - SystemFile1, 2 삭제
                this.progressBarInitialize.Value += 20;
                this.DeleteFolder(this.ParentForm.ParentForm.PathFlashDiskSystemFile1Folder);
                this.progressBarInitialize.Value += 20;
                this.DeleteFolder(this.ParentForm.ParentForm.PathFlashDiskSystemFile2Folder);
                this.progressBarInitialize.Value += 20;

                // SD Card - SystemFile1, 2 이동
                this.CopyFolder(this.ParentForm.ParentForm.PathSDCardSystemFile1Folder, this.ParentForm.ParentForm.PathFlashDiskSystemFile1Folder);
                this.progressBarInitialize.Value += 20;
                this.CopyFolder(this.ParentForm.ParentForm.PathSDCardSystemFile2Folder, this.ParentForm.ParentForm.PathFlashDiskSystemFile2Folder);
                this.progressBarInitialize.Value = 100;

                this.InitializeStep = DataStore.Step3.Step3;
                this.UpdateLabelStatus(this.InitializeStep, this.ParentForm.ParentForm.SystemConfig1.Language);

                this.ParentForm.Enabled = false;
            }
        }
        private void InitializeSystem(DialogResult result)
        {
            if (result == DialogResult.Yes)
            {
                this.InitializeStep = DataStore.Step3.Step2;
                this.UpdateLabelStatus(this.InitializeStep, this.ParentForm.ParentForm.SystemConfig1.Language);

                this.progressBarInitialize.Value = 0;
                // SystemFile 1, 2 RemoveFile 폴더로 이동
                this.MoveToRemoveFileFolder(this.ParentForm.ParentForm.PathSDCardSystemFile1Folder);
                this.progressBarInitialize.Value += 50;
                this.MoveToRemoveFileFolder(this.ParentForm.ParentForm.PathSDCardSystemFile2Folder);
                this.progressBarInitialize.Value = 100;

                this.InitializeStep = DataStore.Step3.Step3;
                this.UpdateLabelStatus(this.InitializeStep, this.ParentForm.ParentForm.SystemConfig1.Language);

                this.ParentForm.Enabled = false;
            }
        }
        private void InitializeCount(int productNumber)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append(Helper.StringZeroFillDigits4(productNumber.ToString()));      // 품번(4)
            sb.Append("0000000");                                                                                   // ExNG 카운트(7)
            sb.Append("0000000");                                                                                   // 상한 카운트(7)
            sb.Append("0000000");                                                                                   // 기준 카운트(7)
            sb.Append("0000000");                                                                                   // 하한 카운트(7)
            sb.Append("0000");                                                                                        // Dummy1(4)
            sb.Append("0000000");                                                                                   // Dummy1(7)
            sb.Append("0000000");                                                                                   // Dummy2(7)
            sb.Append("0000000");                                                                                   // Dummy3(7)
            sb.Append("0000000");                                                                                   // Dummy4(7)

            this.ParentForm.ParentForm.TransferDataStream(CommunicationCommand.Write, CommunicationID.MainBoard, CommunicationAddress.ParameterCount, sb.ToString());
        }

        private void UpdateLabelStatus(DataStore.Step3 step, DataStore.LanguageID language)
        {
            switch (step)
            {
                case DataStore.Step3.Step1:
                    #region Step1
                    switch (language)
                    {
                        case DataStore.LanguageID.Korean:
                            this.labelMessage1.Font = new Font("새굴림", 17, FontStyle.Regular);
                            this.labelMessage1.Text = "초기화를 원하는 항목을 선택해주십시오";
                            this.labelMessage2.Text = "";
                            break;
                        case DataStore.LanguageID.English:
                            this.labelMessage1.Font = new Font("새굴림", 17, FontStyle.Regular);
                            this.labelMessage1.Text = "Please select the item you want to initialize";
                            this.labelMessage2.Text = "";
                            break;
                        case DataStore.LanguageID.Chinese:
                            this.labelMessage1.Font = new Font("새굴림", 17, FontStyle.Regular);
                            this.labelMessage1.Text = "请选择要初始化的项目";
                            this.labelMessage2.Text = "";
                            break;
                        case DataStore.LanguageID.Russian:
                            this.labelMessage1.Font = new Font("새굴림", 12, FontStyle.Regular);
                            this.labelMessage1.Text = "Пожалуйста, выберите элемент,";
                            this.labelMessage2.Font = new Font("새굴림", 12, FontStyle.Regular);
                            this.labelMessage2.Text = "который хотите инициализировать";
                            break;
                        case DataStore.LanguageID.German:
                            this.labelMessage1.Font = new Font("새굴림", 12, FontStyle.Regular);
                            this.labelMessage1.Text = "Bitte wählen Sie das Element aus, das Sie initialisieren möchten";
                            this.labelMessage2.Text = "";
                            break;
                        case DataStore.LanguageID.Spanish:
                            this.labelMessage1.Font = new Font("새굴림", 17, FontStyle.Regular);
                            this.labelMessage1.Text = "Por favor, seleccione el elemento que desea inicializar";
                            this.labelMessage2.Text = "";
                            break;
                        default:
                            break;
                    }
                    #endregion
                    break;
                case DataStore.Step3.Step2:
                    #region Step2
                    switch (language)
                    {
                        case DataStore.LanguageID.Korean:
                            this.labelMessage1.Font = new Font("새굴림", 17, FontStyle.Regular);
                            this.labelMessage1.Text = "초기화 중...";
                            this.labelMessage2.Text = "";
                            break;
                        case DataStore.LanguageID.English:
                            this.labelMessage1.Font = new Font("새굴림", 17, FontStyle.Regular);
                            this.labelMessage1.Text = "Initializing...";
                            this.labelMessage2.Text = "";
                            break;
                        case DataStore.LanguageID.Chinese:
                            this.labelMessage1.Font = new Font("새굴림", 17, FontStyle.Regular);
                            this.labelMessage1.Text = "初始化中...";
                            this.labelMessage2.Text = "";
                            break;
                        case DataStore.LanguageID.Russian:
                            this.labelMessage1.Font = new Font("새굴림", 12, FontStyle.Regular);
                            this.labelMessage1.Text = "Выполняется инициализация...";
                            this.labelMessage2.Text = "";
                            break;
                        case DataStore.LanguageID.German:
                            this.labelMessage1.Font = new Font("새굴림", 12, FontStyle.Regular);
                            this.labelMessage1.Text = "Initialisierung wird ausgeführt...";
                            this.labelMessage2.Text = "";
                            break;
                        case DataStore.LanguageID.Spanish:
                            this.labelMessage1.Font = new Font("새굴림", 17, FontStyle.Regular);
                            this.labelMessage1.Text = "Inicializando...";
                            this.labelMessage2.Text = "";
                            break;
                        default:
                            break;
                    }
                    #endregion
                    break;
                case DataStore.Step3.Step3:
                    #region Step3
                    switch (language)
                    {
                        case DataStore.LanguageID.Korean:
                            this.labelMessage1.Font = new Font("새굴림", 17, FontStyle.Regular);
                            this.labelMessage1.Text = "초기화 완료";
                            this.labelMessage2.Font = new Font("새굴림", 17, FontStyle.Regular);
                            this.labelMessage2.Text = "전원을 끄고 다시 켜주세요.";
                            break;
                        case DataStore.LanguageID.English:
                            this.labelMessage1.Font = new Font("새굴림", 17, FontStyle.Regular);
                            this.labelMessage1.Text = "Initialization complete";
                            this.labelMessage2.Font = new Font("새굴림", 17, FontStyle.Regular);
                            this.labelMessage2.Text = "Reset the power.";
                            break;
                        case DataStore.LanguageID.Chinese:
                            this.labelMessage1.Font = new Font("새굴림", 17, FontStyle.Regular);
                            this.labelMessage1.Text = "初始化完成";
                            this.labelMessage2.Font = new Font("새굴림", 17, FontStyle.Regular);
                            this.labelMessage2.Text = "关掉电源，然后在打开电源";
                            break;
                        case DataStore.LanguageID.Russian:
                            this.labelMessage1.Font = new Font("새굴림", 12, FontStyle.Regular);
                            this.labelMessage1.Text = "Инициализация завершена";
                            this.labelMessage2.Font = new Font("새굴림", 12, FontStyle.Regular);
                            this.labelMessage2.Text = "Выключите питание и снова включите.";
                            break;
                        case DataStore.LanguageID.German:
                            this.labelMessage1.Font = new Font("새굴림", 12, FontStyle.Regular);
                            this.labelMessage1.Text = "Die Initialisierung ist abgeschlossen";
                            this.labelMessage2.Font = new Font("새굴림", 12, FontStyle.Regular);
                            this.labelMessage2.Text = "Mit dem Hauptschalter aus- und einschalten";
                            break;
                        case DataStore.LanguageID.Spanish:
                            this.labelMessage1.Font = new Font("새굴림", 12, FontStyle.Regular);
                            this.labelMessage1.Text = "Inicialización completa";
                            this.labelMessage2.Font = new Font("새굴림", 12, FontStyle.Regular);
                            this.labelMessage2.Text = "Apague la alimentación y luego encienda la alimentación.";
                            break;
                        default:
                            break;
                    }
                    #endregion
                    break;
                default:
                    break;
            }

            this.Refresh();
        }
        public void UpdateDisplayMainBoardInitialization()
        {
            this.timer.Enabled = false;

            this.progressBarInitialize.Value = 100;

            this.InitializeStep = DataStore.Step3.Step3;
            this.UpdateLabelStatus(this.InitializeStep, this.ParentForm.ParentForm.SystemConfig1.Language);

            this.ParentForm.Enabled = false;
        }

        public void DisplayRefresh(SystemStatus status)
        {
            this.ParentForm.ParentForm.CurrentSystemStatus.CurrentDisplay = DataStore.DisplayStore.EquipInitialize;
            this.ParentForm.ParentForm.SetDisplayMode(DataStore.DisplayMode.Menu);
            this.ParentForm.DisplayTitleRoot(this.ParentForm.ParentForm.CurrentSystemStatus);

            this.DefaultSetting();

            if (status.CurrentUser.Group == DataStore.UserGroup.Level4Developer && this.ParentForm.ParentForm.SystemConfig1.IsLogin == true)
                this.DisplayHiddenMenu(true);
            else
                this.DisplayHiddenMenu(false);
        }
        public void DisplayHiddenMenu(bool visible)
        {
            if (visible == false)
            {
                this.buttonBackup.Visible = false;
                this.buttonSystemInitialization.Visible = false;
            }
            else
            {
                this.buttonBackup.Visible = true;
                this.buttonSystemInitialization.Visible = true;
            }
        }
        #endregion

        #region Event Handler
        private void buttonMainBoardLcd_Click(object sender, EventArgs e)
        {
            // 설정된 모든 데이터가 초기화됩니다.
            DialogFormYesNo myDlg = new DialogFormYesNo(this.ParentForm.ParentForm.SystemConfig1.Language, 5);
            DialogResult dr = myDlg.ShowDialog();
            myDlg.Close();
            
            this.Refresh();
            this.InitializeMainBoardLcd(dr);
        }

        private void buttonMainBoard_Click(object sender, EventArgs e)
        {
            // 메인보드에 설정된 데이터가 초기화됩니다.
            DialogFormYesNo myDlg = new DialogFormYesNo(this.ParentForm.ParentForm.SystemConfig1.Language, 7);
            DialogResult dr = myDlg.ShowDialog();
            myDlg.Close();

            this.Refresh();
            this.InitializeMainBoard(dr);
        }

        private void buttonLcd_Click(object sender, EventArgs e)
        {
            // LCD에 설정된 데이터가 초기화됩니다.
            DialogFormYesNo myDlg = new DialogFormYesNo(this.ParentForm.ParentForm.SystemConfig1.Language, 6);
            DialogResult dr = myDlg.ShowDialog();
            myDlg.Close();

            this.Refresh();
            this.InitializeLcd(dr);
        }

        private void buttonBackup_Click(object sender, EventArgs e)
        {
            // 현재 데이터를 백업하시겠습니까?
            DialogFormYesNo myDlg = new DialogFormYesNo(this.ParentForm.ParentForm.SystemConfig1.Language, 23);
            DialogResult dr = myDlg.ShowDialog();
            myDlg.Close();

            this.Refresh();
            this.BackupSystemFile(dr);
        }

        private void buttonSystemInitialization_Click(object sender, EventArgs e)
        {
            // 설정된 모든 데이터가 초기화됩니다.
            DialogFormYesNo myDlg = new DialogFormYesNo(this.ParentForm.ParentForm.SystemConfig1.Language, 5);
            DialogResult dr = myDlg.ShowDialog();
            myDlg.Close();

            this.Refresh();
            this.InitializeSystem(dr);
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            this.FlagTimeout++;
            if (this.FlagTimeout == 10)
            {
                this.timer.Enabled = false;

                // 메인보드 통신 상태 확인해주세요
                DialogFormMessage message = new DialogFormMessage(22, this.ParentForm.ParentForm.SystemConfig1.Language);
                message.ShowDialog();
            }

            this.progressBarInitialize.Value += 2;
        }

        private void buttonBackup2_Click(object sender, EventArgs e)
        {
            bool directoryCheck = false;
            string filePathSystemFileBackup = "", filePathSystemFile = "";
            FileInfo[] files;

            filePathSystemFile = this.ParentForm.ParentForm.PathSDCardSystemFile1Folder;
            filePathSystemFileBackup = this.ParentForm.ParentForm.PathSDCardSystemFileBackupFolder;

            DirectoryInfo dirSystemFileFolder = new DirectoryInfo(filePathSystemFile);
            DirectoryInfo dirSystemFileBackupFolder = new DirectoryInfo(filePathSystemFileBackup);

            // SystemFileBackup 폴더 체크
            directoryCheck = dirSystemFileBackupFolder.Exists;
            if (directoryCheck == false)
                dirSystemFileBackupFolder.Create();
            else
            {
                files = dirSystemFileBackupFolder.GetFiles();

                foreach (FileInfo file in files)
                    file.Delete();
            }

            files = dirSystemFileFolder.GetFiles();

            foreach (FileInfo file in files)
            {
                file.CopyTo(filePathSystemFileBackup + file.Name, true);
            }
        }
        #endregion
    }
}
