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

using INT_LKD_2.Forms;
using INT_LKD_2.DialogForms;
using INT_LKD_2.DataStore;

namespace INT_LKD_2.Controls
{
    public partial class ControlMenuSystemInformation : UserControl
    {
        #region Field
        private FormMenu m_ParentForm;

        private string USBPath = "";
        private string UpdateFileDisplayPath = "";
        private string UpdateFileMainboardPath = "";
        private string RunFilePath = "";
        private string RemoveFolderPath = "";
        #endregion

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

            this.ParentForm = parent;
            this.Initialize();
        }
        #endregion

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

        #region Method
        private void Initialize()
        {
            this.smartGroupBox1.Text = "System > Information";

            this.labelDisplayVersion.Text = "1.1.1";
            this.labelSerialNo.Text = this.ParentForm.ParentForm.SystemConfig.SERIAL_NUMBER;

            this.USBPath = "하드 디스크\\";
            this.UpdateFileDisplayPath = this.USBPath + "UpdateFiles\\";
            this.UpdateFileMainboardPath = this.USBPath + "UpdateFilesMain\\";
            this.RunFilePath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\";
            if (this.RunFilePath.StartsWith("\\F") == true)
                this.RemoveFolderPath = "Flash Disk\\RemoveFile\\";
            else
                this.RemoveFolderPath = "SD Card\\RemoveFile\\";

            this.smartKeyboard1.KeyboardType = SmartX.SmartKeyboard.KEYBOARDTYPES.NORMAL;
            this.smartKeyboard1.Left = 40;
            this.smartKeyboard1.Top = 217;
            this.smartKeyboard1.Width = 832;
            this.smartKeyboard1.Height = 327;
            this.smartKeyboard1.Hide();
        }

        public void UpdateMainBoardVersionMasterDisplay(string version)
        {
            if (version.Length < 8)
                return;

            this.labelControlVersionMaster.Text = version;
        }
        public void UpdateMainBoardVersionSlaveDisplay(string version)
        {
            if (version.Length < 8)
                return;

            this.labelControlVersionSlave.Text = version;
        }
        public void UpdateDisplayTime(DateTime time)
        {
            this.labelCurrentTime.Text = time.ToString("yyyy-MM-dd HH:mm:ss");

            this.upDownHour.Value = time.Hour;
            this.upDownMinute.Value = time.Minute;
        }

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

            DirectoryInfo info = new DirectoryInfo(this.USBPath);
            DirectoryInfo dirFolderUpdateFiles = new DirectoryInfo(this.UpdateFileDisplayPath);

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

                    if (newFiles.Length == 0)
                    {
                        ret = Define.E_UpdateCheck.NoFile;
                    }
                    else
                    {
                        ret = Define.E_UpdateCheck.Success;
                    }
                }
                else
                {
                    ret = Define.E_UpdateCheck.NoUpdateFolder;
                }
            }
            else
            {
                ret = Define.E_UpdateCheck.NoUsbMomery;
            }

            return ret;
        }
        private void DisplayProgramUpdateCheck(DialogResult result)
        {
            Define.E_UpdateCheck check = Define.E_UpdateCheck.Fail;

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

                if (check == Define.E_UpdateCheck.Success)
                {
                    DialogFormProgressBar progressBar = new DialogFormProgressBar(1, this.ParentForm.ParentForm.SystemConfig.LANGUAGE, this.ParentForm.ParentForm);
                    DialogResult dialogResult = progressBar.ShowDialog();
                }
                else if (check == Define.E_UpdateCheck.NoUsbMomery)
                {
                    DialogFormMessage message = new DialogFormMessage(5, this.ParentForm.ParentForm.SystemConfig.LANGUAGE);
                    message.ShowDialog();
                }
                else if (check == Define.E_UpdateCheck.NoUpdateFolder)
                {
                    DialogFormMessage message = new DialogFormMessage(9, this.ParentForm.ParentForm.SystemConfig.LANGUAGE);
                    message.ShowDialog();
                }
                else if (check == Define.E_UpdateCheck.NoFile)
                {
                    DialogFormMessage message = new DialogFormMessage(7, this.ParentForm.ParentForm.SystemConfig.LANGUAGE);
                    message.ShowDialog();
                }
            }
        }
     
        private Define.E_UpdateCheck CheckMainboardMasterError()
        {
            Define.E_UpdateCheck ret = Define.E_UpdateCheck.Fail;
            FileInfo[] newFiles;
            bool isUpdateFile = false;
            string fileName = "";

            DirectoryInfo info = new DirectoryInfo(this.USBPath);
            DirectoryInfo dirFolderUpdateFiles = new DirectoryInfo(this.UpdateFileMainboardPath);

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

                    foreach (FileInfo file in newFiles)
                    {
                        fileName = file.Name.ToLower();

                        if (fileName == "ibd902m.bin")
                        {
                            isUpdateFile = true;
                            this.UpdateFileMainboardPath += "ibd902m.bin";

                            break;
                        }
                    }

                    if (newFiles.Length == 0)
                    {
                        ret = Define.E_UpdateCheck.NoFile;
                    }
                    else
                    {
                        ret = Define.E_UpdateCheck.Success;
                    }
                }
                else
                {
                    ret = Define.E_UpdateCheck.NoUpdateFolder;
                }
            }
            else
            {
                ret = Define.E_UpdateCheck.NoUsbMomery;
            }

            return ret;
        }
        private void MainboardMasterProgramUpdateCheck(DialogResult result)
        {
            Define.E_UpdateCheck check = Define.E_UpdateCheck.Fail;
            this.UpdateFileMainboardPath = this.USBPath + "UpdateFilesMain\\";

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

                if (check == Define.E_UpdateCheck.Success)
                {
                    long a = 0;
                    byte[] byteData, version;
                    string sVersion = "";
                    FileStream fs = new FileStream(this.UpdateFileMainboardPath, FileMode.Open, FileAccess.Read);

                    version = new byte[8];
                    BinaryReader br = new BinaryReader(fs);
                    a = br.BaseStream.Length;
                    int i = int.Parse(a.ToString());
                    byteData = br.ReadBytes(i);
                    version[0] = byteData[20];
                    version[1] = byteData[21];
                    version[2] = byteData[22];
                    version[3] = byteData[23];
                    version[4] = byteData[24];
                    version[5] = byteData[25];
                    version[6] = byteData[26];
                    version[7] = byteData[27];
                    sVersion = Encoding.UTF8.GetString(version, 0, version.Length);

                    DialogFormYesNo myDlg = new DialogFormYesNo(this.ParentForm.ParentForm.SystemConfig.LANGUAGE, 3, this.ParentForm.ParentForm.SystemConfig.MAINBOARD_VERSION_MASTER, sVersion);
                    if (myDlg.ShowDialog() == DialogResult.Yes)
                    {
                        this.ParentForm.ParentForm.CloseSmartUartLink();

                        DialogFormProgressBar progressBar = new DialogFormProgressBar(2, this.ParentForm.ParentForm.SystemConfig.LANGUAGE, this.ParentForm.ParentForm.UpdateForMain, this.ParentForm.ParentForm, Define.E_BoardMode.Master);
                        DialogResult dialogResult = progressBar.ShowDialog();
                        if (dialogResult == DialogResult.Cancel)
                            this.ParentForm.ParentForm.OpenSmartUartLink();
                    }
                    else
                        return;
                }
                else if (check == Define.E_UpdateCheck.NoUsbMomery)
                {
                    DialogFormMessage message = new DialogFormMessage(5, this.ParentForm.ParentForm.SystemConfig.LANGUAGE);
                    message.ShowDialog();
                }
                else if (check == Define.E_UpdateCheck.NoUpdateFolder)
                {
                    DialogFormMessage message = new DialogFormMessage(9, this.ParentForm.ParentForm.SystemConfig.LANGUAGE);
                    message.ShowDialog();
                }
                else if (check == Define.E_UpdateCheck.NoFile)
                {
                    DialogFormMessage message = new DialogFormMessage(7, this.ParentForm.ParentForm.SystemConfig.LANGUAGE);
                    message.ShowDialog();
                }
            }
        }

        private Define.E_UpdateCheck CheckMainboardSlaveError()
        {
            Define.E_UpdateCheck ret = Define.E_UpdateCheck.Fail;
            FileInfo[] newFiles;
            bool isUpdateFile = false;
            string fileName = "";

            DirectoryInfo info = new DirectoryInfo(this.USBPath);
            DirectoryInfo dirFolderUpdateFiles = new DirectoryInfo(this.UpdateFileMainboardPath);

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

                    foreach (FileInfo file in newFiles)
                    {
                        fileName = file.Name.ToLower();

                        if (fileName == "ibd902s.bin")
                        {
                            isUpdateFile = true;
                            this.UpdateFileMainboardPath += "ibd902s.bin";

                            break;
                        }
                    }

                    if (newFiles.Length == 0)
                    {
                        ret = Define.E_UpdateCheck.NoFile;
                    }
                    else
                    {
                        ret = Define.E_UpdateCheck.Success;
                    }
                }
                else
                {
                    ret = Define.E_UpdateCheck.NoUpdateFolder;
                }
            }
            else
            {
                ret = Define.E_UpdateCheck.NoUsbMomery;
            }

            return ret;
        }
        private void MainboardSlaveProgramUpdateCheck(DialogResult result)
        {
            Define.E_UpdateCheck check = Define.E_UpdateCheck.Fail;
            this.UpdateFileMainboardPath = this.USBPath + "UpdateFilesSlave\\";

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

                if (check == Define.E_UpdateCheck.Success)
                {
                    long a = 0;
                    byte[] byteData, version;
                    string sVersion = "";
                    FileStream fs = new FileStream(this.UpdateFileMainboardPath, FileMode.Open, FileAccess.Read);

                    version = new byte[8];
                    BinaryReader br = new BinaryReader(fs);
                    a = br.BaseStream.Length;
                    int i = int.Parse(a.ToString());
                    byteData = br.ReadBytes(i);
                    version[0] = byteData[20];
                    version[1] = byteData[21];
                    version[2] = byteData[22];
                    version[3] = byteData[23];
                    version[4] = byteData[24];
                    version[5] = byteData[25];
                    version[6] = byteData[26];
                    version[7] = byteData[27];
                    sVersion = Encoding.UTF8.GetString(version, 0, version.Length);

                    DialogFormYesNo myDlg = new DialogFormYesNo(this.ParentForm.ParentForm.SystemConfig.LANGUAGE, 3, this.ParentForm.ParentForm.SystemConfig.MAINBOARD_VERSION_SLAVE, sVersion);
                    if (myDlg.ShowDialog() == DialogResult.Yes)
                    {
                        this.ParentForm.ParentForm.CloseSmartUartLink();

                        DialogFormProgressBar progressBar = new DialogFormProgressBar(2, this.ParentForm.ParentForm.SystemConfig.LANGUAGE, this.ParentForm.ParentForm.UpdateForMain, this.ParentForm.ParentForm, Define.E_BoardMode.Slave);
                        DialogResult dialogResult = progressBar.ShowDialog();
                        if (dialogResult == DialogResult.OK)
                        {
                            this.ParentForm.ParentForm.OpenSmartUartLink();
                        }
                    }
                    else
                        return;
                }
                else if (check == Define.E_UpdateCheck.NoUsbMomery)
                {
                    DialogFormMessage message = new DialogFormMessage(5, this.ParentForm.ParentForm.SystemConfig.LANGUAGE);
                    message.ShowDialog();
                }
                else if (check == Define.E_UpdateCheck.NoUpdateFolder)
                {
                    DialogFormMessage message = new DialogFormMessage(9, this.ParentForm.ParentForm.SystemConfig.LANGUAGE);
                    message.ShowDialog();
                }
                else if (check == Define.E_UpdateCheck.NoFile)
                {
                    DialogFormMessage message = new DialogFormMessage(7, this.ParentForm.ParentForm.SystemConfig.LANGUAGE);
                    message.ShowDialog();
                }
            }
        }

        public void DisplayRefresh()
        {
            DateTime currentTime = DateTime.Now;

            this.ParentForm.ParentForm.CurrentSystemStatus.CurrentDisplayMode = Define.E_DisplayModeStore.Information;
            this.ParentForm.ParentForm.SetDisplayMode(Define.E_EquipmentMode.Menu);

            this.smartKeyboard1.Hide();

            this.ParentForm.ParentForm.TransferDataStream_Master(CommunicationCommand.Read, CommunicationID.MainBoardMaster, CommunicationAddress._1502_ProgramVersion, "");
            this.ParentForm.ParentForm.TransferDataStream_Slave(CommunicationCommand.Read, CommunicationID.MainBoardSlave, CommunicationAddress._1502_ProgramVersion, "");

            this.labelCurrentTime.Text = currentTime.ToString("yyyy-MM-dd HH:mm:ss");

            this.upDownYear.Value = currentTime.Year;
            this.upDownMonth.Value = currentTime.Month;
            this.upDownDate.Value = currentTime.Day;
            this.upDownHour.Value = currentTime.Hour;
            this.upDownMinute.Value = currentTime.Minute;

            this.buttonSave.Visible = false;

            switch (this.ParentForm.ParentForm.CurrentSystemStatus.CurrentUser.Group)
            {
                case Define.E_UserGroup.None:
                    this.Enabled = false;
                    break;
                case Define.E_UserGroup.Level1:
                    this.Enabled = this.ParentForm.ParentForm.CurrentUserGroup.Level1.IsMenuInformation;
                    break;
                case Define.E_UserGroup.Level2:
                    this.Enabled = this.ParentForm.ParentForm.CurrentUserGroup.Level1.IsMenuInformation;
                    break;
                case Define.E_UserGroup.Level3:
                    this.Enabled = this.ParentForm.ParentForm.CurrentUserGroup.Level1.IsMenuInformation;
                    break;
                case Define.E_UserGroup.Admin:
                    this.Enabled = true;
                    break;
                case Define.E_UserGroup.Developer:
                    this.Enabled = true;
                    break;
                case Define.E_UserGroup.NotLogin:
                    this.Enabled = false;
                    break;
                case Define.E_UserGroup.LogOut:
                    this.Enabled = false;
                    break;
                default:
                    break;
            }
        }
        #endregion

        #region Event Handler
        private void labelSerialNo_Click(object sender, EventArgs e)
        {
            DialogFormPasswordKeyPad password = new DialogFormPasswordKeyPad(4, this.ParentForm.ParentForm.SystemConfig.LANGUAGE);
            DialogResult dialogResult = password.ShowDialog();
            if (dialogResult == DialogResult.OK)
            {
                this.labelSerialNo.BackGroundColor = Color.White;

                this.smartKeyboard1.TargetInputObject = this.labelSerialNo;

                this.smartKeyboard1.Show();
            }
        }

        private void smartKeyboard1_OnLabelKeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                e.Handled = true;

                this.smartKeyboard1.Hide();

                this.labelSerialNo.BackGroundColor = Color.FromArgb(224, 224, 224);

                this.ParentForm.ParentForm.SystemConfig.SERIAL_NUMBER = this.labelSerialNo.Text;
                this.ParentForm.ParentForm.SaveSystemConfigurationFile(this.ParentForm.ParentForm.SystemConfig);
            }
            else if (e.KeyChar == 27) // ESC 눌렀을 때
            {
                e.Handled = true;

                this.labelSerialNo.BackGroundColor = Color.FromArgb(224, 224, 224);
                this.smartKeyboard1.Hide();
            }
        }
        private void smartKeyboard1_OnXKeyClick(object sender, EventArgs e)
        {
            this.labelSerialNo.BackGroundColor = Color.FromArgb(224, 224, 224);
            this.smartKeyboard1.Hide();
        }

        private void buttonUpdateMainboardMaster_Click(object sender, EventArgs e)
        {
            //DialogFormYesNo myDlg = new DialogFormYesNo(this.ParentForm.ParentForm.SystemConfig.LANGUAGE, 3);
            //DialogResult dr = myDlg.ShowDialog();
            //myDlg.Close();

            this.Refresh();

            this.MainboardMasterProgramUpdateCheck(DialogResult.Yes);
        }
        private void buttonUpdateMainboardSlave_Click(object sender, EventArgs e)
        {
            this.Refresh();

            this.MainboardSlaveProgramUpdateCheck(DialogResult.Yes);
        }
        private void buttonUpdateDisplay_Click(object sender, EventArgs e)
        {
            DialogFormYesNo myDlg = new DialogFormYesNo(this.ParentForm.ParentForm.SystemConfig.LANGUAGE, 3);
            DialogResult dr = myDlg.ShowDialog();
            myDlg.Close();

            this.Refresh();

            this.DisplayProgramUpdateCheck(dr);
        }

        private void buttonTimeSetting_Click(object sender, EventArgs e)
        {
            if (this.ParentForm.ParentForm.timerSystem.Enabled == true)
                this.ParentForm.ParentForm.timerSystem.Enabled = false;
            this.buttonSave.Visible = true;
        }
        private void buttonSave_Click(object sender, EventArgs e)
        {
            DateTime time;
            try
            {
                time = new DateTime(int.Parse(this.upDownYear.Value.ToString()), int.Parse(this.upDownMonth.Value.ToString()),
                    int.Parse(this.upDownDate.Value.ToString()), int.Parse(this.upDownHour.Value.ToString()), int.Parse(this.upDownMinute.Value.ToString()), 00);
            }
            catch
            {
                this.DisplayRefresh();
                return;
            }

            this.ParentForm.ParentForm.SetCurrentTime(time);
            this.ParentForm.ParentForm.timerSystem.Enabled = true;
            this.buttonSave.Visible = false;
        }
        #endregion

        private void smartButton1_Click(object sender, EventArgs e)
        {
            this.ParentForm.ParentForm.SystemConfig.LANGUAGE = Define.E_LanguageID.English;
            this.ParentForm.ParentForm.SaveSystemConfigurationFile(this.ParentForm.ParentForm.SystemConfig);
        }
    }
}
