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 SmartX;
using ITC81DB_2.Forms;
using ITC81DB_2.DialogForms;
using ITC81DB_2_ImageDll;

namespace ITC81DB_2.Controls
{
    public partial class ControlCenterEquipUpdate : UserControl
    {
        #region Field
        private FormMenu m_ParentForm;
        private Define.E_Step3 UpdateStep;

        private int Check;

        private string USBPath = "";
        private string UpdateFilePath = "";
        private string OldFilePath = "";
        private string RemoveFolderPath = "";

        private List<string> DllName = new List<string>();
        private List<long> LongOldDllFileLastWriteTime = new List<long>();
        private List<long> LongNewDllFileLastWriteTime = new List<long>();
        #endregion

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

            this.ParentForm = parent;

            this.InitializeDesign();
            this.DefaultSetting();
        }
        #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.SystemConfig.Language == Define.E_LanguageID.English)
            {
            }
            else if (this.ParentForm.ParentForm.SystemConfig.Language == Define.E_LanguageID.Chinese)
            {
            }
            else if (this.ParentForm.ParentForm.SystemConfig.Language == Define.E_LanguageID.Czech)
            {
            }
            else if (this.ParentForm.ParentForm.SystemConfig.Language == Define.E_LanguageID.Spanish)
            {
            }
            else
            {
            }
        }
        private void DefaultSetting()
        {
            this.UpdateStep = Define.E_Step3.Step1;
            this.UpdateLabelStatus(this.UpdateStep, this.ParentForm.ParentForm.SystemConfig.Language);
        }

        private Define.E_UpdateCheck CheckError()
        {
            Define.E_UpdateCheck ret = Define.E_UpdateCheck.Fail;
            FileInfo[] newFiles;

            if (Directory.Exists("Hard Disk\\") == true)
                this.USBPath = "Hard Disk\\";
            else if (Directory.Exists("하드 디스크\\") == true)
                this.USBPath = "하드 디스크\\";
            else
                this.USBPath = "하드 디스크\\";

            this.UpdateFilePath = this.USBPath + "UpdateFiles\\";

            DirectoryInfo info = new DirectoryInfo(this.USBPath);
            DirectoryInfo directoryFolderUpdateFiles = new DirectoryInfo(this.UpdateFilePath);

            // USB 장착 유무 확인
            if (info.Exists == true)
            {
                // USB에 UpdateFiles 유무 확인
                if (directoryFolderUpdateFiles.Exists == true)
                {
                    newFiles = directoryFolderUpdateFiles.GetFiles();

                    if (newFiles.Length == 0)
                    {
                        ret = Define.E_UpdateCheck.NotFile;
                    }
                    else
                    {
                        ret = Define.E_UpdateCheck.Success;
                    }
                }
                else
                {
                    ret = Define.E_UpdateCheck.NotUpdateFolder;
                }
            }
            else
            {
                ret = Define.E_UpdateCheck.NotUsbMomery;
            }

            return ret;
        }
        private void ProgramUpdate()
        {
            FileInfo[] newFiles;
            DirectoryInfo directoryFolderUpdateFiles = new DirectoryInfo(this.UpdateFilePath);
            if (directoryFolderUpdateFiles.Exists == false)
                directoryFolderUpdateFiles.Create();

            this.Check = 0;

            this.UpdateFilePath = this.USBPath + "UpdateFiles\\";
            this.OldFilePath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\";
            if (this.OldFilePath.StartsWith("\\F") == true)
                this.RemoveFolderPath = "Flash Disk\\RemoveFile\\";
            else
                this.RemoveFolderPath = "SD Card\\RemoveFile\\";

            newFiles = directoryFolderUpdateFiles.GetFiles();

            this.progressBarUpdate.Value += 20;

            this.TreatmentRemoveOldFile();
            this.TreatmentCopyNewFile(newFiles);

            this.progressBarUpdate.Value += 100;
            this.ParentForm.Enabled = false;
            this.UpdateStep = Define.E_Step3.Step3;
            this.UpdateLabelStatus(this.UpdateStep, this.ParentForm.ParentForm.SystemConfig.Language);
        }
        private void TreatmentRemoveOldFile()
        {
            bool removeFolderCheck = false;
            FileInfo[] oldFiles;
            DirectoryInfo directoryFolderRun = new DirectoryInfo(this.OldFilePath);
            DirectoryInfo directoryFolderRemove = new DirectoryInfo(this.RemoveFolderPath);

            removeFolderCheck = directoryFolderRemove.Exists;
            oldFiles = directoryFolderRun.GetFiles();

            if (removeFolderCheck == false)
                directoryFolderRemove.Create();

            foreach (FileInfo subFile in oldFiles)
                subFile.MoveTo(this.RemoveFolderPath + DateTime.Now.ToString("yyyyMMddHHmmss") + subFile.Name.ToString());

            this.progressBarUpdate.Value += 20;
        }
        private void TreatmentCopyNewFile(FileInfo[] newFile)
        {
            // 새 파일 복사
            foreach (FileInfo subFile in newFile)
                subFile.CopyTo(this.OldFilePath + subFile.Name.ToString());

            this.progressBarUpdate.Value += 20;
        }
        private void UpdateLabelStatus(Define.E_Step3 step, Define.E_LanguageID language)
        {
            switch (step)
            {
                case Define.E_Step3.Step1:
                    #region Step1
                    switch (language)
                    {
                        case Define.E_LanguageID.Korean:
                            this.labelMessage1.Text = "USB를 본체에 삽입 하십시오";
                            this.labelMessage2.Text = "삽입 후 하단 'Update'버튼을 눌러주십시오";
                            break;
                        case Define.E_LanguageID.English:
                            this.labelMessage1.Text = "Please insert usb into the device";
                            this.labelMessage2.Text = "Press the bottom button after inserting";
                            break;
                        case Define.E_LanguageID.Chinese:
                            this.labelMessage1.Text = "请将 USB 插入设备";
                            this.labelMessage2.Text = "请点击下端的按钮更新按钮";
                            break;
                        case Define.E_LanguageID.Spanish:
                            this.labelMessage1.Text = "Por favor, inserte USB en el dispositivo";
                            this.labelMessage2.Text = "Presione el botón inferior después de insertar";
                            break;
                        case Define.E_LanguageID.Czech:
                            break;
                        default:
                            break;
                    } 
                    #endregion
                    break;
                case Define.E_Step3.Step2:
                    #region Step2
                    switch (language)
                    {
                        case Define.E_LanguageID.Korean:
                            this.labelMessage1.Text = "업데이트 중...";
                            this.labelMessage2.Text = "USB를 본체에서 분리하지 마십시오";
                            break;
                        case Define.E_LanguageID.English:
                            this.labelMessage1.Text = "Updating...";
                            this.labelMessage2.Text = "Do not remove the USB from the device";
                            break;
                        case Define.E_LanguageID.Chinese:
                            this.labelMessage1.Text = "更新中……";
                            this.labelMessage2.Text = "请勿断开USB";
                            break;
                        case Define.E_LanguageID.Spanish:
                            this.labelMessage1.Text = "Actualizando....";
                            this.labelMessage2.Text = "No desconecte el USB del cuerpo.";
                            break;
                        case Define.E_LanguageID.Czech:
                            break;
                        default:
                            break;
                    } 
                    #endregion
                    break;
                case Define.E_Step3.Step3:
                    #region Step3
                    this.labelMessage2.ForeColor = Color.Red;
                    switch (language)
                    {
                        case Define.E_LanguageID.Korean:
                            this.labelMessage1.Text = "프로그램 업데이트 완료";
                            this.labelMessage2.Text = "전원을 끄고 다시 켜주세요";
                            break;
                        case Define.E_LanguageID.English:
                            this.labelMessage1.Text = "Program update complete";
                            this.labelMessage2.Text = "Reset the system";
                            break;
                        case Define.E_LanguageID.Chinese:
                            this.labelMessage1.Text = "系统更新完成";
                            this.labelMessage2.Text = "关掉电源，然后在打开电源";
                            break;
                        case Define.E_LanguageID.Spanish:
                            this.labelMessage1.Text = "Actualización del programa completa. Apague la ";
                            this.labelMessage2.Text = "alimentación y luego encienda la alimentación.";
                            break;
                        case Define.E_LanguageID.Czech:
                            break;
                        default:
                            break;
                    } 
                    #endregion
                    break;
                default:
                    break;
            }

            this.Refresh();
        }
        private void ProgramUpdateCheck(DialogResult result)
        {
            Define.E_UpdateCheck check = Define.E_UpdateCheck.Fail;

            if (result == DialogResult.Yes)
            {
                check = this.CheckError();

                if (check == Define.E_UpdateCheck.Success)
                {
                    this.buttonUpdate.Enabled = false;
                    this.UpdateStep = Define.E_Step3.Step2;
                    this.UpdateLabelStatus(this.UpdateStep, this.ParentForm.ParentForm.SystemConfig.Language);

                    this.ProgramUpdate();
                }
                else if (check == Define.E_UpdateCheck.NotUsbMomery)
                {
                    DialogFormMessage message = new DialogFormMessage(5, this.ParentForm.ParentForm.SystemConfig.Language);
                    message.ShowDialog();
                }
                else if (check == Define.E_UpdateCheck.NotUpdateFolder)
                {
                    DialogFormMessage message = new DialogFormMessage(9, this.ParentForm.ParentForm.SystemConfig.Language);
                    message.ShowDialog();
                }
                else if (check == Define.E_UpdateCheck.NotFile)
                {
                    DialogFormMessage message = new DialogFormMessage(7, this.ParentForm.ParentForm.SystemConfig.Language);
                    message.ShowDialog();
                }
            }
        }

        public void DisplayRefresh(SystemStatus status)
        {
            this.ParentForm.ParentForm.CurrentSystemStatus.CurrentDisplay = Define.E_DisplayStore.EquipUpdate;
            this.ParentForm.ParentForm.SetDisplayMode(Define.E_DisplayMode.Menu);
            this.ParentForm.DisplayTitleRoot(this.ParentForm.ParentForm.CurrentSystemStatus);

            this.DefaultSetting();
        }
        #endregion

        #region Event Handler
        private void buttonUpdate_Click(object sender, EventArgs e)
        {
            DialogFormYesNo myDlg = new DialogFormYesNo(this.ParentForm.ParentForm.SystemConfig.Language, 3);
            DialogResult dr = myDlg.ShowDialog();
            myDlg.Close();

            this.Refresh();

            this.ProgramUpdateCheck(dr);
        }
        #endregion
    }
}
