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.Forms;
using ITC81DB.DialogForms;
using ITC81DB_ImageDll;

namespace ITC81DB.Controls
{
    public partial class ControlCenterEquipUpdate : UserControl
    {
        #region Field
        private FormMenu m_ParentForm;
        private DataStore.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.SystemConfig1.Language == DataStore.LanguageID.English)
            {
                this.buttonUpdate.Text = "Update";
            }
            else if (this.ParentForm.ParentForm.SystemConfig1.Language == DataStore.LanguageID.Chinese)
            {
                this.buttonUpdate.Text = "更新";
            }
            else if (this.ParentForm.ParentForm.SystemConfig1.Language == DataStore.LanguageID.Czech)
            {
            }
            else if (this.ParentForm.ParentForm.SystemConfig1.Language == DataStore.LanguageID.Russian)
            {
                this.buttonUpdate.Text = "Обновить";
            }
            else if (this.ParentForm.ParentForm.SystemConfig1.Language == DataStore.LanguageID.German)
            {
                this.buttonUpdate.Text = "Aktualisierung";
            }
            else if (this.ParentForm.ParentForm.SystemConfig1.Language == DataStore.LanguageID.Spanish)
            {
                this.buttonUpdate.Text = "Actualizar";
            }
            else
            {
                this.buttonUpdate.Text = "Update";
            }
        }
        private void DefaultSetting()
        {
            this.UpdateStep = DataStore.Step3.Step1;
            this.UpdateLabelStatus(this.UpdateStep, this.ParentForm.ParentForm.SystemConfig1.Language);
            this.labelDisplayVer.Text = FormMain.DisplayVersion;
        }

        private DataStore.UpdateCheck CheckError()
        {
            DataStore.UpdateCheck ret = DataStore.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 dirFolderUpdateFiles = new DirectoryInfo(this.UpdateFilePath);

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

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

            return ret;
        }
        #region V3 이후 LCD 프로그램 업데이트 시 DB파일 자동 Conversion 기능 추가
        //private void ProgramUpdate()
        //{
        //    // SD Card\\PreVersionBackup 폴더 생성
        //    DirectoryInfo dirPreVersionFolder = new DirectoryInfo(this.ParentForm.ParentForm.PathPreVersionFolder);
        //    if (dirPreVersionFolder.Exists == true)
        //        // PreVersion 폴더 -> Remove 폴더
        //        Helper.MoveToRemoveFolder(this.ParentForm.ParentForm.PathPreVersionFolder);
        //    else
        //        dirPreVersionFolder.Create();

        //    this.progressBarUpdate.Value += 20;

        //    // 현재 시스템 폴더 1 -> PreVersionBackup 폴더
        //    Helper.MoveToFolder(this.ParentForm.ParentForm.PathSDCardSystemFile1Folder, this.ParentForm.ParentForm.PathPreVersionSystemFile1Folder);

        //    this.progressBarUpdate.Value += 20;

        //    // 현재 시스템 폴더 2 -> PreVersionBackup 폴더
        //    Helper.MoveToFolder(this.ParentForm.ParentForm.PathSDCardSystemFile2Folder, this.ParentForm.ParentForm.PathPreVersionSystemFile2Folder);

        //    this.progressBarUpdate.Value += 20;

        //    // 현재 Run 폴더 -> PreVersionBackup 폴더
        //    Helper.MoveToFolder(this.ParentForm.ParentForm.PathLaunchRunFolder, this.ParentForm.ParentForm.PathPreVersionRunFolder);

        //    this.progressBarUpdate.Value += 20;

        //    // USB - UpdateFiles 폴더 -> 현재 Run 폴더
        //    this.UpdateFilePath = this.USBPath + "UpdateFiles\\";
        //    Helper.CopyToFolder(this.UpdateFilePath, this.ParentForm.ParentForm.PathLaunchRunFolder);

        //    this.progressBarUpdate.Value += 100;
        //    this.ParentForm.Enabled = false;
        //    this.UpdateStep = DataStore.Step3.Step3;
        //    this.UpdateLabelStatus(this.UpdateStep, this.ParentForm.ParentForm.SystemConfig1.Language);
        //}
        #endregion
        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.progressBarUpdate.Value += 20;

            this.TreatmentCopyNewFile(newFiles);

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

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

            if (removeFolderCheck == false)
                directoryFolderRemove.Create();
            //else
            //{
            //    removeFiles = directoryFolderRemove.GetFiles();
            //    foreach (FileInfo file in removeFiles)
            //        file.Delete();
            //}

            foreach (FileInfo subFile in oldFiles)
                subFile.MoveTo(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(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 = "USB를 본체에 삽입 하십시오";
                            this.labelMessage2.Font = new Font("새굴림", 17, FontStyle.Regular);
                            this.labelMessage2.Text = "삽입 후 하단 'Update'버튼을 눌러주십시오";
                            break;
                        case DataStore.LanguageID.English:
                            this.labelMessage1.Font = new Font("새굴림", 17, FontStyle.Regular);
                            this.labelMessage1.Text = "Please insert usb into the device";
                            this.labelMessage2.Font = new Font("새굴림", 17, FontStyle.Regular);
                            this.labelMessage2.Text = "Press the bottom button after inserting";
                            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.German:
                            this.labelMessage1.Font = new Font("새굴림", 12, FontStyle.Regular);
                            this.labelMessage1.Text = "USB nicht vom Gerät trennen";
                            this.labelMessage2.Font = new Font("새굴림", 12, FontStyle.Regular);
                            this.labelMessage2.Text = "Drücken Sie nach dem USB-Anschluss die untere Taste";
                            break;
                        case DataStore.LanguageID.Russian:
                            this.labelMessage1.Font = new Font("새굴림", 12, FontStyle.Regular);
                            this.labelMessage1.Text = "Пожалуйста, вставьте USB в устройство";
                            this.labelMessage2.Font = new Font("새굴림", 12, FontStyle.Regular);
                            this.labelMessage2.Text = "Нажмите нижнюю кнопку после вставки";
                            break;
                        case DataStore.LanguageID.Spanish:
                            this.labelMessage1.Font = new Font("새굴림", 12, FontStyle.Regular);
                            this.labelMessage1.Text = "Por favor, inserte USB en el dispositivo";
                            this.labelMessage2.Font = new Font("새굴림", 12, FontStyle.Regular);
                            this.labelMessage2.Text = "Presione el botón inferior después de insertar";
                            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.Font = new Font("새굴림", 17, FontStyle.Regular);
                            this.labelMessage2.Text = "USB를 본체에서 분리하지 마십시오";
                            break;
                        case DataStore.LanguageID.English:
                            this.labelMessage1.Font = new Font("새굴림", 17, FontStyle.Regular);
                            this.labelMessage1.Text = "Updating...";
                            this.labelMessage2.Font = new Font("새굴림", 17, FontStyle.Regular);
                            this.labelMessage2.Text = "Do not remove the USB from the device";
                            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 = "请勿断开USB";
                            break;
                        case DataStore.LanguageID.German:
                            this.labelMessage1.Font = new Font("새굴림", 12, FontStyle.Regular);
                            this.labelMessage1.Text = "Aktualisierung….";
                            this.labelMessage2.Font = new Font("새굴림", 12, FontStyle.Regular);
                            this.labelMessage2.Text = "USB nicht vom Gerät trennen";
                            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 = "Не отключайте USB";
                            break;
                        case DataStore.LanguageID.Spanish:
                            this.labelMessage1.Font = new Font("새굴림", 12, FontStyle.Regular);
                            this.labelMessage1.Text = "Actualizando....";
                            this.labelMessage2.Font = new Font("새굴림", 12, FontStyle.Regular);
                            this.labelMessage2.Text = "No desconecte el USB del cuerpo.";
                            break;
                        default:
                            break;
                    }
                    #endregion
                    break;
                case DataStore.Step3.Step3:
                    #region Step3
                    this.labelMessage2.ForeColor = Color.Red;
                    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 = "Program update complete";
                            this.labelMessage2.Font = new Font("새굴림", 17, FontStyle.Regular);
                            this.labelMessage2.Text = "Reset the system";
                            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.German:
                            this.labelMessage1.Font = new Font("새굴림", 12, FontStyle.Regular);
                            this.labelMessage1.Text = "Programmaktualisierung abgeschlossen";
                            this.labelMessage2.Font = new Font("새굴림", 12, FontStyle.Regular);
                            this.labelMessage2.Text = "Mit dem Hauptschalter aus- und einschalten";
                            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.Spanish:
                            this.labelMessage1.Font = new Font("새굴림", 12, FontStyle.Regular);
                            this.labelMessage1.Text = "Actualización del programa 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();
        }
        private void ProgramUpdateCheck(DialogResult result)
        {
            DataStore.UpdateCheck check = DataStore.UpdateCheck.Fail;

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

                if (check == DataStore.UpdateCheck.Success)
                {
                    this.buttonUpdate.Enabled = false;
                    this.UpdateStep = DataStore.Step3.Step2;
                    this.UpdateLabelStatus(this.UpdateStep, this.ParentForm.ParentForm.SystemConfig1.Language);

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

        public void DisplayRefresh(SystemStatus status)
        {
            this.ParentForm.ParentForm.CurrentSystemStatus.CurrentDisplay = DataStore.DisplayStore.EquipUpdate;
            this.ParentForm.ParentForm.SetDisplayMode(DataStore.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.SystemConfig1.Language, 3);
            DialogResult dr = myDlg.ShowDialog();
            myDlg.Close();

            this.Refresh();

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