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 Cosmos.BaseFrame;
using Cosmos.UserFrame;
using Cosmos.ServiceProvider;
using Cosmos.Common;
using Cosmos.CommonManager;
using Cosmos.UI;

using Cosmos.Win;

namespace TableConfiguration
{
    public partial class frmBackground : Form
    {
        private static Cosmos.ServiceProvider.Activator m_ServiceProvider = new Cosmos.ServiceProvider.Activator();

        private SManager sManager = new SManager();                                 //이 객체를 통해 업무 Service 호출
        private StateServer StateObject = (StateServer)StateServer.GetInstance();   //StateObject : StateServer Object(객체)
        private PosStatus m_cPosStatus = new PosStatus();                           //기본정보 참조
        
        private ITableUs m_cTableSvr = null;
        private IDataCommonUs m_cDataCommon = null;                                 // POS 공통함수 인터페이스

        /// <summary>
        /// 사용자ID 
        /// </summary>
        private string userId = string.Empty;
        /// <summary>
        /// 사용자명
        /// </summary>
        private string userNm = string.Empty;
        /// <summary>
        /// 원 사용자ID
        /// </summary>
        private string orgUserId = string.Empty;
        /// <summary>
        /// 원 사용자명 
        /// </summary>
        private string orgUserNm = string.Empty;



        public frmBackground(string[] args)
        {
            InitializeComponent();

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

            m_cPosStatus = (PosStatus)StateObject.POS;      //POS 기본정보

            // 서비스
            m_cTableSvr = (ITableUs)sManager.InitServiceInstance(ServiceLists.BSV_TABLE.DLL, ServiceLists.BSV_TABLE.TABLE_SERVICE);
            m_cDataCommon = (IDataCommonUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_COMMON);

            // 명령인수
            if (args.Length > 0)
            {
                this.userId = args[0].Trim();
            }
        }

        private void Form_Load(object sender, EventArgs e)
        {
            try
            {
                UserLog.WriteLogFile(UserCom.LOG_IOS, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                                      System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                                      System.Reflection.MethodBase.GetCurrentMethod().Name + "()", "");
                PosOLEDevice.SetEventHandle(null);
                this.SetBounds(0, 0, 1024, 768);
            }
            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 Form_Shown(object sender, EventArgs e)
        {
            try
            {
                string ret = UserCom.RST_ERR;

                // 환경설정 파일 읽기
                IServiceUs cPgmStart = (IServiceUs)sManager.InitServiceInstance(ServiceLists.BSV_OPEN_CLOSE.DLL, ServiceLists.BSV_OPEN_CLOSE.PROGRAM_START);
                ret = cPgmStart.Execute(new string[] { });
                if (ret != UserCom.RST_OK)
                {
                }

                // POS 마스터 읽기
                IServiceUs cLoadMstSrv = (IServiceUs)sManager.InitServiceInstance(ServiceLists.BSV_OPEN_CLOSE.DLL, ServiceLists.BSV_OPEN_CLOSE.LOAD_MASTER_INFO);
                ret = cLoadMstSrv.Execute(new string[] { });
                if (ret != UserCom.RST_OK)
                {
                }

                // 테이블 서비스 데이터베이스 연결 
                m_cTableSvr.DBConnection();

                // POS 설정정보 확인 
                if (CheckConfigInfo() == false)
                {
                    this.DialogResult = System.Windows.Forms.DialogResult.Abort;
                    this.Close();
                    return;
                }

                //
                if (m_cPosStatus.ScnMst.ThemeColor.Trim().Length != 6)
                {
                    m_cPosStatus.ScnMst.ThemeColor = "022187238";
                }
                // 
                if (string.IsNullOrWhiteSpace(m_cPosStatus.Base.FONT))
                    m_cPosStatus.Base.FONT = SystemFonts.DefaultFont.Name;

                // 점주로그온 
                bool checkUser = true;
                if (string.IsNullOrWhiteSpace(this.userId) == false)
                {
                    // 관리자 조회
                    IMasterUs cService = (IMasterUs)sManager.InitServiceInstance(ServiceLists.ASV_MASTER.DLL, ServiceLists.ASV_MASTER.CASHIER_MASTER);
                    DataTable dt = cService.Select(new string[] { m_cPosStatus.Base.StoreNo, CmUtil.RightH(this.userId, 3) });
                    if (dt == null || dt.Rows.Count == 0)
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0309);
                    }
                    else
                    {
                        string div = CmUtil.GetDataRowStr(dt.Rows[0], PosMst.MST_USER.DATA.CASHIER_DIV);
                        if (div == PosConst.CASHIER_DIV.OWNER || div == PosConst.CASHIER_DIV.MANAGER)
                        {
                            this.userNm = CmUtil.GetDataRowStr(dt.Rows[0], PosMst.MST_USER.DATA.CASHIER_NM);
                            checkUser = false;
                        }
                    }
                }
                if (checkUser)
                {
                    ret = WinBasic.ShowForm(new string[] { FormManager.FORM_LOG_ON, PosKey.MENU_KEY.REGISTER_ADMIN });
                    if (ret == UserCom.RST_ERR)
                    {
                        this.Close();
                        return;
                    }
                    try
                    {
                        string[] user = ret.Split('|');
                        this.userId = user[0].Trim();
                        this.userNm = user[1].Trim();
                    }
                    catch
                    {
                        this.Close();
                        return;
                    }
                }
                orgUserId = m_cPosStatus.Base.CashierNo;
                orgUserNm = m_cPosStatus.Base.CashierName;
                m_cPosStatus.Base.CashierNo = userId;
                m_cPosStatus.Base.CashierName = userNm;

                // 테이블편집 실행 
                frmTableEditor frm = new frmTableEditor();
                frm.ShowDialog();

                // 사용자 원복 
                m_cPosStatus.Base.CashierNo = this.orgUserId;
                m_cPosStatus.Base.CashierName = this.orgUserNm;

                Application.Exit();
            }
            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 Form_Closing(object sender, FormClosingEventArgs e)
        {
            try
            {
                UserLog.WriteLogFile(UserCom.LOG_IOS, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                                      System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                                      System.Reflection.MethodBase.GetCurrentMethod().Name + "()", "");

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

        /// <summary>
        /// 설정정보 체크 
        /// </summary>
        /// <returns></returns>
        private bool CheckConfigInfo()
        {
            try
            {
                if (string.IsNullOrWhiteSpace(m_cPosStatus.Base.CmpCd))
                {
                    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0492);
                    return false;
                }
                if (string.IsNullOrWhiteSpace(m_cPosStatus.Base.StoreNo))
                {
                    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0493);
                    return false;
                }
                if (string.IsNullOrWhiteSpace(m_cPosStatus.Base.PosType))
                {
                    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0378);
                    return false;
                }
                if (m_cPosStatus.Base.PosType != PosConst.POS_TYPE.DEFERRED_PAYMENT)
                {
                    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0494);
                    return false;
                }
                if (m_cPosStatus.Base.PosCommunicationType != PosConst.MAIN_POS_DIV.MAIN_POS)
                {
                    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0668);
                    return false;
                }


                return 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);
                return false;
            }
        }

    }
}
