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

using Cosmos.UserFrame;
using Cosmos.BaseFrame;
using Cosmos.Common;
using Cosmos.CommonManager;
using Cosmos.ServiceProvider;

namespace Cosmos.Win
{
    public partial class frmSignPadUpdate : Form
    {
        #region 변수 선언
        private ISignPadUs m_cDeviceSignPad = null;                                 // 서명패드
        private IDeviceUpdate m_SignPadUpdate = null;                              // 서명패드 업데이트
        private StateServer StateObject = (StateServer)StateServer.GetInstance();   //StateObject : StateServer Object(객체)
        private SManager sManager = new SManager();                                 // 이 객체를 통해 업무 Service 호출
        private PosStatus m_cPosStatus = new PosStatus();                           // 기본정보 참조
        private IICReaderUs m_objICReader = null;                                   // IC 리더기

        /// <summary>
        /// Device 상태 정보 객체
        /// </summary>
        public DeviceStatus m_cDevStatus = null;

        private const int WM_USER = 0x400;
        private const int WM_TTTT = WM_USER + 2;

        private bool m_FirstSetting = true;
        private int sDownResult = 0;
        private int nUpdateCnt = 0;

        private const int WM_SIGNPAD_UPGRADE_RESULT = WM_USER + 1;
        private const int WM_SIGNPAD_UPGRADE_PROGRESS = WM_USER + 2;

        private int nCreateCode = 0;
        private string sWorkBiz = "";

        private string sWorkBizMsg = "";

        private int ipb = 0;                                  // ProgreeBar 카운트

        private string sSetImgUpdateFiles = string.Empty;     // 이미지 업데이트 파일
        private string sSetAviUpdateFile = string.Empty;      // 동영상 업데이트 파일
        private string sSetFirmUpdateFile = string.Empty;     // 펌웨어 업데이트 파일

        private string SIGNPAD_FIRMWARE_Path = BaseCom.NxDonglePath + @"FIRMWARE\";
        private string SIGNPAD_AVI_Path = BaseCom.NxDonglePath + @"AVI\";
        private string SIGNPAD_IMG_Path = BaseCom.NxDonglePath + @"IMG\";

        private DataTable m_DataTable = new DataTable();
        /// <summary>
        /// 처리대상 정보
        /// </summary>
        public DataTable SetDataTable { set { this.m_DataTable = value; } get { return m_DataTable; } }            

        #endregion 변수 선언

        #region 생성자 & 소멸자
        public frmSignPadUpdate()
        {
            InitializeComponent();

            base.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.ResizeRedraw, true);
            //this.UpdateStyles();

            m_cPosStatus = (PosStatus)StateObject.POS;      // POS 기본정보
            m_cDeviceSignPad = (ISignPadUs)sManager.InitServiceInstance(ServiceLists.AGENT_OLEDEVICE.DLL, ServiceLists.AGENT_OLEDEVICE.DEVICE_SIGNPAD);
            m_SignPadUpdate = (IDeviceUpdate)sManager.InitServiceInstance(ServiceLists.BSV_BASIC.DLL, ServiceLists.BSV_BASIC.SIGNPAD_UPDATE);
            m_objICReader = (IICReaderUs)sManager.InitServiceInstance(ServiceLists.AGENT_OLEDEVICE.DLL, ServiceLists.AGENT_OLEDEVICE.DEVICE_ICREADER);
            m_cDevStatus = (DeviceStatus)StateObject.DEVICE;
        }

        private void frmSignPadUpdate_Load(object sender, EventArgs e)
        {
            UserLog.WriteLogFile(UserCom.LOG_IOS, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", "");
            InitControl();
        }

        private void frmSignPadUpdate_FormClosing(object sender, FormClosingEventArgs e)
        {
            UserLog.WriteLogFile(UserCom.LOG_IOS, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", lblTitle.Text);
        }
        #endregion 생성자 & 소멸자

        #region 폼 컨트롤 초기화
        /// <summary>
        /// 폼 컨트롤 초기화
        /// </summary>
        private void InitControl()
        {
            try
            {
                #region 변수 초기화
                nUpdateCnt = 0;
                ipb = 0;
                sWorkBizMsg = "";
                lblCount.Text = "";
                pbWork.Minimum = 0;
                pbWork.Maximum = 100;

                pbWork.Visible = false;

                m_FirstSetting = true;
                btnEsc.Tag = "0";
                #endregion 변수 초기화

                FormManager.SetFormAllControlFont(this, m_cPosStatus.Base.FONT);
                FormManager.SetTextBoxGlobalInfo(this, m_cPosStatus.Global.m_stCultureMaster.nGroupingDigits, m_cPosStatus.Global.m_stCultureMaster.strGroupingSymbol
                    , m_cPosStatus.Global.m_stCultureMaster.nDecimalDigits, m_cPosStatus.Global.m_stCultureMaster.strDecimalSymbol);
                FormManager.MovePopUpForm(this, false, m_cPosStatus.Sale.ScreenSizeUser);

                picBack.Image = ImageManager.GetImage(Cosmos.BaseFrame.BaseCom.NxImgPath, ImageManager.POP_SIZE_S);

                btnExit.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.BTN_CLOSE);
                if (btnExit.Image != null) btnExit.Text = "";

                lblMessage.Text = MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0612);

                btnYes.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0025);
                btnNo.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0026);
                btnEsc.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0010);

                btnEsc.Visible = false;
                btnYes.Visible = true;
                btnNo.Visible = true;

                this.TopMost = true;

                nUpdateCnt = m_SignPadUpdate.SignPadUpdateCnt(ref sSetImgUpdateFiles, ref sSetAviUpdateFile, ref sSetFirmUpdateFile);

                if (nUpdateCnt == 0)
                {
                    WinManager.ErrorMessage(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0577));
                    this.Close();
                    return;
                }

                // 서명패드 업데이트 제어코드 생성
                nCreateCode = m_cDeviceSignPad.SignPad_Create_UpdateCode();

                // 서명패드 다운로드 결과 전송
                m_cDeviceSignPad.SignPad_Update_Return(nCreateCode, this.Handle, WM_SIGNPAD_UPGRADE_RESULT);
                m_cDeviceSignPad.SignPad_Update_Progress_Return(nCreateCode, this.Handle, WM_SIGNPAD_UPGRADE_PROGRESS);

            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", "Process Exception !!! " + ex.Message);
            }
        }
        #endregion 폼 컨트롤 초기화

        #region Control Event
        private void btnYes_Click(object sender, EventArgs e)
        {
            bool bRet = false;
            string sRet = UserCom.RST_ERR;

            int nImgCnt = 0;

            int nFirstNm = 0;
            string[] sFiles = null;
            bool bNumCheck = false;

            try
            {
                bRet = false;

                // 서명패드 연결 체크
                string retVal = string.Empty;

                if (m_cDeviceSignPad.GetSignPadInfo(ref retVal) == true)
                {
                    System.Threading.Thread.Sleep(100);

                    sRet = UserCom.RST_OK;
                }
                System.Threading.Thread.Sleep(100);
                // 서명패드 연결 체크

                // 서명패드 연결 실패시 업데이트 불가
                if (sRet == UserCom.RST_ERR)
                {
                    CommonManager.WinManager.ErrorMessage(Cosmos.CommonManager.POS_MESSAGE.ERROR.MSG_0387);
                    return;
                }

                pbWork.Visible = true;
                btnEsc.Visible = true;
                btnYes.Visible = false;
                btnNo.Visible = false;

                // 서명패드 이미지 확인
                if (sSetImgUpdateFiles.Length > 0)
                {
                    sFiles = sSetImgUpdateFiles.Split('|');
                }

                if (sFiles != null && sFiles.Count() > 0)
                {
                    if (File.Exists(SIGNPAD_IMG_Path + sFiles[0].ToString()) == true)
                    {
                        sWorkBiz = PosConst.PGM_UPDATE_TYPE.POSDOWN_GROUP_60;

                        lblMessage.Text = MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0636);
                        sWorkBizMsg = MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0636) + "...{0} %";

                        m_cDeviceSignPad.SignPad_Update_FileClear(nCreateCode);

                        for (int i = 0; sFiles.Count() > i; i++)
                        {
                            bNumCheck = int.TryParse(sFiles[i].Substring(0, 1), out nFirstNm);

                            if (bNumCheck == true)
                            {
                                if (nFirstNm == 1 || nFirstNm == 2 || nFirstNm == 3 || nFirstNm == 4)
                                {
                                    bRet = m_cDeviceSignPad.SetImage_SignPad_Update(nCreateCode, nFirstNm, SIGNPAD_IMG_Path + sFiles[i].ToString());
                                    nImgCnt = nImgCnt + 1;
                                }
                                else
                                {
                                    continue;
                                }
                            }
                        }

                        if (nImgCnt > 0)
                        {
                            bRet = m_cDeviceSignPad.SignPad_Start(nCreateCode, m_cPosStatus.Base.OlePosSignPadSerialPortNumber);
                        }

                        if (bRet != true)
                        {
                            sFiles = null;
                            SetDataState(sWorkBiz, false);
                            DeleteFile(sWorkBiz, 1);
                            btnYes_Click(null, null);
                        }

                        return;
                    }
                }

                // 동영상
                if (File.Exists(SIGNPAD_AVI_Path + sSetAviUpdateFile) == true)
                {
                    sWorkBiz = PosConst.PGM_UPDATE_TYPE.POSDOWN_GROUP_50;

                    lblMessage.Text = MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0635);
                    sWorkBizMsg = MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0635) + "...{0} %";

                    bRet = m_cDeviceSignPad.SetAvi_SignPad_Update(nCreateCode, SIGNPAD_AVI_Path + sSetAviUpdateFile);
                    if (bRet == true)
                    {
                        //성공
                        bRet = m_cDeviceSignPad.SignPad_Start(nCreateCode, m_cPosStatus.Base.OlePosSignPadSerialPortNumber);
                    }

                    if (bRet != true)
                    {
                        SetDataState(sWorkBiz, false);
                        DeleteFile(sWorkBiz, 1);
                        btnYes_Click(null, null);
                    }
                    return;
                }

                // 펌웨어
                if (File.Exists(SIGNPAD_FIRMWARE_Path + sSetFirmUpdateFile) == true)
                {
                    sWorkBiz = PosConst.PGM_UPDATE_TYPE.POSDOWN_GROUP_40;

                    lblMessage.Text = MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0672);
                    sWorkBizMsg = MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0672) + "...{0} %";

                    bRet = m_cDeviceSignPad.SetFirmware_SignPad_Update(nCreateCode, SIGNPAD_FIRMWARE_Path + sSetFirmUpdateFile);

                    if (bRet == true)
                    {
                        //성공
                        bRet = m_cDeviceSignPad.SignPad_Start(nCreateCode, m_cPosStatus.Base.OlePosSignPadSerialPortNumber);
                    }

                    if (bRet != true)
                    {
                        SetDataState(sWorkBiz, false);
                        DeleteFile(sWorkBiz, 1);
                        btnYes_Click(null, null);
                    }
                    return;
                }

                //return;

            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     ex.Message);
                this.Close();
            }

            //this.Close();
            return;
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            btnEsc_Click(btnExit, null);
        }

        private void btnEsc_Click(object sender, EventArgs e)
        {
            try
            {
                if ((string)btnEsc.Tag != "1")
                {
                    // 처리 상태 저장
                    SetDataState(sWorkBiz, false);

                    // 업데이트 취소
                    m_cDeviceSignPad.SignPad_Update_Stop(nCreateCode);

                    // 자원해제
                    int nRet = m_cDeviceSignPad.SignPad_Update_Destroy(nCreateCode);
                    this.DialogResult = DialogResult.Cancel;
                }
                else
                {
                    this.DialogResult = DialogResult.OK;
                }

                // 취소시 모든파일 삭제
                // 취소시켰다고 파일이 남아 있을 경우 추후 펌웨어 업데이트 진행시 업데이트 파일이 꼬일 수도 있다.
                DeleteFile("", 0);
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     ex.Message);
            }

            this.Close();
        }

        private void btnNo_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        #endregion Control Event

        #region User Method
        // 윈도우 메시지 처리를 위한 오버라이드 함수.
        protected override void WndProc(ref Message m)
        {
            try
            {
                if (m.Msg == WM_SIGNPAD_UPGRADE_RESULT)
                {
                    sDownResult = (int)m.WParam;
                    if (sDownResult == 1)
                    {
                        UpdateResult(true);
                    }
                    else if (sDownResult == 2)
                    {
                        btnEsc_Click(null, null);
                    }
                }

                if (m.Msg == WM_SIGNPAD_UPGRADE_PROGRESS)
                {
                    if (m_FirstSetting == true)
                    {
                        ipb = 0;

                        m_FirstSetting = false;

                        SetProgreeBar(ipb, (Int32)m.LParam);
                    }
                    SetProgreeBar(ipb++, (Int32)m.LParam);
                }
                base.WndProc(ref m);
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     ex.Message);
            }

        }

        #region 상태 진행바
        /// <summary>
        /// 상태 진행바
        /// </summary>
        /// <param name="iMaxPercent"></param>
        private void SetProgreeBar(int iValue, int iMaxValue)
        {
            try
            {
                double nPercent = CmUtil.DoubleMultiplication(CmUtil.DoubleDivision(iValue, iMaxValue), 100);

                pbWork.Visible = true;
                pbWork.Minimum = 0;
                pbWork.Maximum = 100;
                pbWork.Value = (int)Math.Round(nPercent, 0, MidpointRounding.AwayFromZero);
                pbWork.Update();

                lblCount.Visible = true;
                lblCount.Text = string.Format(sWorkBizMsg, Math.Round(nPercent, 0, MidpointRounding.AwayFromZero).ToString());
                lblCount.Update();
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }

        private void UpdateResult(bool bRetFlag)
        {
            try
            {
                // 메세지 표시
                if (sWorkBiz == PosConst.PGM_UPDATE_TYPE.POSDOWN_GROUP_40)
                {
                    lblMessage.Text = MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0615);
                }
                else if (sWorkBiz == PosConst.PGM_UPDATE_TYPE.POSDOWN_GROUP_50)
                {
                    lblMessage.Text = MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0613);
                }
                else if (sWorkBiz == PosConst.PGM_UPDATE_TYPE.POSDOWN_GROUP_60)
                {
                    lblMessage.Text = MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0614);
                }

                lblMessage.Update();

                // 처리 상태 저장
                SetDataState(sWorkBiz, true);

                // 이미지 정보가 있을 경우 초기화
                if (sSetImgUpdateFiles.Length > 0)
                {
                    sSetImgUpdateFiles = "";
                }

                // 파일이 1개 이상일 경우 다음 업데이트를 진행한다.
                if (nUpdateCnt > 1)
                {
                    m_cDeviceSignPad.SignPad_Update_Stop(nCreateCode);
                    nUpdateCnt = nUpdateCnt - 1;

                    m_FirstSetting = true;

                    pbWork.Value = 0;
                    pbWork.Update();
                    DeleteFile(sWorkBiz, 1);
                    System.Threading.Thread.Sleep(500);
                    btnYes_Click(null, null);
                }
                else
                {
                    DeleteFile(sWorkBiz, 1);
                    btnEsc.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0009);
                    btnEsc.Tag = "1";
                }
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     ex.Message);
            }
        }

        private void DeleteFile(string sWorkBizFile, int nFlag)
        {
            try
            {
                if (nFlag == 0)
                {
                    CmUtil.DeleteDirectoryInFile(SIGNPAD_IMG_Path, 2);
                    CmUtil.DeleteDirectoryInFile(SIGNPAD_AVI_Path, 2);
                    CmUtil.DeleteDirectoryInFile(SIGNPAD_FIRMWARE_Path, 2);
                }
                else
                {
                    if (sWorkBiz == PosConst.PGM_UPDATE_TYPE.POSDOWN_GROUP_60)
                    {
                        //DirectoryInfo dir = new DirectoryInfo(SIGNPAD_IMG_Path);
                        //dir.Delete(true);
                        CmUtil.DeleteDirectoryInFile(SIGNPAD_IMG_Path, 2);

                    }

                    if (sWorkBiz == PosConst.PGM_UPDATE_TYPE.POSDOWN_GROUP_50)
                    {
                        //DirectoryInfo dir = new DirectoryInfo(SIGNPAD_AVI_Path);
                        //dir.Delete(true);
                        CmUtil.DeleteDirectoryInFile(SIGNPAD_AVI_Path, 2);
                    }

                    if (sWorkBiz == PosConst.PGM_UPDATE_TYPE.POSDOWN_GROUP_40)
                    {
                        //DirectoryInfo dir = new DirectoryInfo(SIGNPAD_FIRMWARE_Path);
                        //dir.Delete(true);
                        CmUtil.DeleteDirectoryInFile(SIGNPAD_FIRMWARE_Path, 2);
                    }
                }

                

                return;

            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     ex.Message);
            }
        }
        #endregion

        #endregion User Method

        #region 처리 상태 저장
        private void SetDataState(string sGroup, bool bState)
        {
            try
            {
                foreach (DataRow dr in m_DataTable.Rows)
                {
                    string sGroupCheck = CmUtil.MidH(dr["KIND"].ToString(), 0, 2).Trim();
                    if (sGroupCheck == sGroup)  
                    {
                        dr["APP_TYPE"] = (bState == true) ? ItemConst.PGM_DOWN_STATE.Update_OK : ItemConst.PGM_DOWN_STATE.Update_Fail;
                        break;
                    }
                }

            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     ex.Message);
            }
        }
        #endregion 
    }
}
