using System;
using System.Drawing;
using System.Windows.Forms;
using System.Data;

using Cosmos.BaseFrame;
using Cosmos.UserFrame;
using Cosmos.ServiceProvider;
using Cosmos.Common;
using Cosmos.CommonManager;
using System.Collections;
using System.IO;
using System.Diagnostics;
using System.Net.NetworkInformation;
using System.Text;

/*-----------------------------------------------------------------------------------------------*/
// 설      명 : 주변장치 상태 List
// 작  성  자 : 
// 변경  이력 : 
/*-----------------------------------------------------------------------------------------------*/
namespace Cosmos.Win
{
    public partial class frmDeviceStatusSearch : Form
    {
        #region Variable

        private SManager sManager = new SManager();                                 // 이 객체를 통해 업무 Service 호출
        private StateServer StateObject = (StateServer)StateServer.GetInstance();   // StateObject : StateServer Object (객체)
        private PosStatus m_cPosStatus = new PosStatus();                           // 기본정보 참조
        private TranStatus m_cTrnStatus = new TranStatus();                         // 거래정보 참조
        private PosOLEDevice.DelegateOlePos delegatePos; 

        private IDataProcessUs m_cDataSrv = null;
        private IDataCommonUs m_cDataCommon = null;                                 // POS 공통함수 인터페이스
        private IDatabaseSQL m_cSqlDbService = null;                                // 데이터베이스 관리
        private IServiceUs m_cDeviceSrv = null;                                     // 디바이스 관리
        private CmMessage m_cDeviceList = null;                                     // 디바이스 목록 

        private string m_sPosMenuKeyIn;
        public string PosMenuKeyIn { set { m_sPosMenuKeyIn = value; } get { return m_sPosMenuKeyIn; } }

        private bool bNotDoubleClik = false;                                        // 더블 클릭 방지용


        private string m_sPosMenuKey;                                               // 입력코드
        /// <summary>
        /// 할인 구분
        /// </summary>
        public string SetPosMenuKey { set { this.m_sPosMenuKey = value; } }

        /// <summary>
        /// 체크할 주변장치 목록
        /// </summary>
        private string[] aDeviceList = new string[] {
                    "POSPRINTER",
                    "ICREADER",
                    "SIGNPAD",
                    "CATTERMINAL",
                    "SCALE",
                    "SCALEPOLEDISP",
                    "LABELPRINTER",
                    //"CASHDRAWER",
                    //"SCANNER",
                    //"MSR",
                    "NETWORK"
                    };
        #endregion
        
        #region 생성자 & 소멸자
        /// <summary>
        /// 생성자
        /// </summary>
        public frmDeviceStatusSearch()
        {
            InitializeComponent();

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

            m_cPosStatus = (PosStatus)StateObject.POS;      // POS 기본정보
            m_cTrnStatus = (TranStatus)StateObject.TRAN;    // POS 거래정보
            
            m_cDataSrv = (IDataProcessUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_SERVICE);
            m_cDataCommon = (IDataCommonUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_COMMON);
            m_cSqlDbService = (IDatabaseSQL)sManager.InitServiceInstance(ServiceLists.AGENT_DATABASE.DLL, ServiceLists.AGENT_DATABASE.DATABASE_MSSQL);
            // 주변장비 체크 서비스 인스턴스 활성화
            m_cDeviceSrv = (IServiceUs)sManager.InitServiceInstance(ServiceLists.BSV_OPEN_CLOSE.DLL, ServiceLists.BSV_OPEN_CLOSE.DEVICE_SERVICE);

            // 주변장치 목록 체크
            m_cDeviceList = CmMessage.MakeMessageFromFile(BaseCom.NxIniPath + PosConst.INI_FILE_NAME.PosDevice);
        }

        /// <summary>
        /// 폼로드
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmDeviceStatusList_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();
        }

        /// <summary>
        /// 폼클로즈
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmDeviceStatusList_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);
        }

        /// <summary>
        /// 폼엑티브
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmDeviceStatusList_Activated(object sender, EventArgs e)
        {
            PosOLEDevice.SetEventHandle(delegatePos);
        }

        /// <summary>
        /// 폼디엑티브
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmDeviceStatusList_Deactivate(object sender, EventArgs e)
        {
            PosOLEDevice.SetEventHandle(null);
        }
        #endregion 생성자 & 소멸자
        
        #region 폼 컨트롤 초기화
        /// <summary>
        /// 폼 컨트롤 초기화
        /// </summary>
        private void InitControl()
        {
            string sRet = UserCom.RST_ERR;
            try
            {
                //this.BackColor = Color.FromArgb(240, 248, 253);
                picBack.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.POP_SIZE_800X600);
                //this.Size = new Size(1024, 768);
                //this.Location = new Point(0, 0);

                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);

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

                lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0840);
                lblDeviceInfo.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0847);
                lblNetworkInfo.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0848);

                lblPrinter.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0849);
                lblScanner.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0850);
                lblICReder.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0851);
                lblSignpad.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0097);
                lblLabelPrinter.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0853);
                lblCAT.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0854);
                lblScale.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0855);
                lblScalePoleDisp.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0695);
                lblMSR.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0857);
                lblCashdraw.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0693);
                lblPos.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0377);
                lblServer.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0860);

                bNotDoubleClik = false;

                this.StartPosition = FormStartPosition.CenterParent;

                for (int i = 0; i < aDeviceList.Length; i++)
                {
                    string sDeviceName = aDeviceList[i].ToString();

                    DisplayDeviceStatus(sDeviceName, UserCom.RST_RETRY);
                }
                picNetworkX.Visible = false;
                
                tmStart.Enabled = true;
            }
            catch (Exception ex)
            {
               WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }         
        #endregion
         
        #region 버튼 입력 처리
        private void btnExit_Click(object sender, EventArgs e)
        {
            try
            {
                this.DialogResult = DialogResult.Cancel;
                this.Close();
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }
        #endregion
         
        #region 버튼 입력 처리
        /// <summary>
        /// 버튼 입력 처리
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnProc_Click(object sender, EventArgs e)
        {
            string sRet = UserCom.RST_ERR;
            try
            {
                if (bNotDoubleClik) return;
                bNotDoubleClik = true;

                Cosmos.UI.CsmButton btnSelect = (Cosmos.UI.CsmButton)sender;

                if (WinManager.QuestionMessage(POS_MESSAGE.ERROR.MSG_0529) == false) return;

                WinManager.ShowSearchMessage(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0361), this);
                sRet = m_cDeviceSrv.Execute(new string[] { btnSelect.Tag.ToString() });
                DisplayDeviceStatus(btnSelect.Tag.ToString(), sRet);

            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
            finally
            {
                bNotDoubleClik = false;
                WinManager.HideSearchMessage();
            }
        }
        #endregion

        #region 장비 체크
        private void LS_Device_Check_Search()
        {
            string sRet = UserCom.RST_ERR;
            try
            {
                for (int i = 0; i < aDeviceList.Length; i++)
                {
                    string sDeviceName = aDeviceList[i].ToString();

                    if (m_cDeviceList.GetMessage(sDeviceName).GetMessageValue("UseFlag") != PosConst.DEVICE_USE_FLAG.YES_USE)
                    {
                        DisplayDeviceStatus(sDeviceName, UserCom.RST_IGNORE);
                    }
                    else
                    {
                        sRet = m_cDeviceSrv.Execute(new string[] { sDeviceName });
                        DisplayDeviceStatus(sDeviceName, sRet);
                    }

                    SetProgreeBar(i, aDeviceList.Length);
                }

                if (m_cPosStatus.Base.CommSvrIp.Trim() != "")
                {
                    sRet = SetServerSysDateTime();
                    //sRet = CheckNetworkOnline(m_cPosStatus.Base.CommSvrIp);
                    DisplayDeviceStatus("NETWORK", sRet);
                }
            }
            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 DisplayDeviceStatus(string pDeviceName, string pStatus)
        {
            try
            {
                switch (pDeviceName)
                {
                    case "POSPRINTER":
                        SetImage(this.btnPrinter,  pStatus, pDeviceName);
                        m_cPosStatus.Base.OlePosPrinterStatus = pStatus;
                        break;
                    case "SCANNER":
                        SetImage(this.btnScanner,  pStatus, pDeviceName);
                        m_cPosStatus.Base.OlePosScannerStatus = pStatus;
                        break;
                    case "ICREADER":
                        SetImage(this.btnICReder,  pStatus, pDeviceName);
                        m_cPosStatus.Base.OlePosICReaderStatus = pStatus;
                        break;
                    case "SIGNPAD":
                        SetImage(this.btnSignpad, pStatus, pDeviceName);
                        m_cPosStatus.Base.OlePosSignPadStatus = pStatus;
                        break;
                    case "LABELPRINTER":
                        SetImage(this.btnLabelPrinter, pStatus, pDeviceName);
                        m_cPosStatus.Base.OlePosLabelPrinterStatus = pStatus;
                        break;
                    case "CATTERMINAL":
                        SetImage(this.btnCAT,  pStatus, pDeviceName);
                        m_cPosStatus.Base.OlePosCATStatus = pStatus;
                        break;
                    case "SCALE":
                        SetImage(this.btnScale, pStatus, pDeviceName);
                        m_cPosStatus.Base.OlePosScaleStatus = pStatus;
                        break;
                    case "MSR":
                        SetImage(this.btnMSR, pStatus, pDeviceName);
                        m_cPosStatus.Base.OlePosMsrStatus = pStatus;
                        break;
                    case "CASHDRAWER":
                        SetImage(this.btnCashdraw,  pStatus, pDeviceName);
                        m_cPosStatus.Base.OlePosCashDrawerStatus = pStatus;
                        break;
                    case "SCALEPOLEDISP":
                        SetImage(this.btnScalePoleDisp, pStatus, pDeviceName);
                        m_cPosStatus.Base.OlePosScalePoleDispStatus = pStatus;
                        break;
                    case "NETWORK":
                        SetImage(this.btnNetwork,  pStatus, pDeviceName);
                        m_cPosStatus.Base.OlePosNetworkStatus = pStatus;          
                        picNetworkX.Visible = (pStatus != UserCom.RST_OK) ? true : false;
                        break;
                    case "":
                        break;
                }
            }
            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 SetImage(Cosmos.UI.CsmButton btnDevice, string sStatus, string pDeviceName)
        {
            Image imgBack = null;
            string sTextStatus = UserCom.RST_ERR;
            Color sColor = Color.DarkGray;
            try
            {
                if (sStatus == UserCom.RST_OK)//OK
                {
                    imgBack = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.DEVICE_OK);
                    sTextStatus = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0076);
                    sColor = Color.Green;
                    btnDevice.Enabled = true;
                }
                else if (sStatus == UserCom.RST_ERR)//NG
                {
                    imgBack = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.DEVICE_NG);
                    sTextStatus = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0862);
                    sColor = Color.Red;
                    btnDevice.Enabled = true;
                }
                else if (sStatus == UserCom.RST_IGNORE) //PASS (미사용)
                {
                    imgBack = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.DEVICE_PASS);
                    sTextStatus = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0861);
                    sColor = Color.DarkGray;
                    btnDevice.Enabled = false;
                }
                else if (sStatus == UserCom.RST_RETRY) // 초기
                {
                    imgBack = null;
                    sTextStatus = "";
                    sColor = Color.White;
                    btnDevice.Enabled = false;
                }

                //btnDevice.Image = imgBack;
                btnDevice.BackColor = sColor;
                btnDevice.ForeColor = Color.White;

                btnDevice.Text = sTextStatus;
                btnDevice.Tag = pDeviceName;

                //picX.Visible = (sStatus == UserCom.RST_ERR) ? true : false;

            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }

        #endregion

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

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

                System.Threading.Thread.Sleep(300);
                Application.DoEvents();
            }
            catch
            {
                return;
            }
        }
        #endregion

        #region 타이머
        /// <summary>
        /// 당일 걸래 조회 타이머
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tmStart_Tick(object sender, EventArgs e)
        {
            string sRet = UserCom.RST_ERR;

            try
            {
                tmStart.Enabled = false;

                // 주변장치 상태 체크
                LS_Device_Check_Search();
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }
        #endregion 
        
        #region OnLine 상태체크
        /// <summary>
        /// Get network online status with Ping check. (Ping체크로 network Online상태를 취득한다,)
        /// </summary>
        /// <param name="pHostAddress">Ip address</param>
        /// <returns>True : online  false : Offline</returns>
        private string  CheckNetworkOnline(string pHostAddress)
        {
            string sRet = UserCom.RST_ERR;
            try
            {
                //Ping Check (Ping 체크)
                Ping pingSender = new Ping();
                PingOptions optins = new PingOptions();
                optins.DontFragment = true;
                string data = "aaa";
                byte[] buffer = Encoding.ASCII.GetBytes(data);
                int timeout = 120;
                PingReply reply = pingSender.Send(pHostAddress, timeout, buffer, optins);

                if (reply.Status == IPStatus.Success) sRet = UserCom.RST_OK;
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
            return sRet;
        }
        #endregion

        #region 서버 시간 동기화 - 서버 접속 체크용으로 사용
        /// <summary>
        /// 서버 시간 동기화
        /// </summary>
        public string  SetServerSysDateTime()
        {
            string sRet = UserCom.RST_ERR;
            try
            {
                // 서버 시간 동기화
                ISvr2Tran m_cSvr2Tran = (ISvr2Tran)sManager.InitServiceInstance(ServiceLists.BSV_SALE.DLL, ServiceLists.BSV_SALE.SVR2TRAN);
                sRet = m_cSvr2Tran.ServerSysDateTime();
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
            return sRet;
        }
        #endregion 
    }
}
