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;

namespace TableConfiguration
{
    /// <summary>
    /// 작업대기 메시지 
    /// </summary>
    public partial class frmWaitMessage : Form
    {
        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;

        /// <summary>
        /// 작업구분(메뉴구분)
        /// </summary>
        public string WorkType { set; private get; }
        /// <summary>
        /// 작업결과 
        /// </summary>
        public string WorkResult { private set; get; }

        /// <summary>
        /// 층 마스터 
        /// </summary>
        public List<Column.MST_FLOOR.FLOOR_DATA> FloorMaster { set; get; }
        /// <summary>
        /// 테이블 마스터 
        /// </summary>
        public List<Column.MST_TABLE.TABLE_DATA> TableMaster { set; get; }

        /// <summary>
        /// 생성자
        /// </summary>
        public frmWaitMessage()
        {
            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);

        }

        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 + "()", "");

                this.Tag = "START";
                this.WorkResult = UserCom.RST_ERR;
                this.picBack.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.SCH_MESSAGE_BOX);

                FormManager.MovePopUpForm(this, false, m_cPosStatus.Sale.ScreenSizeUser);
                FormManager.SetFormAllControlFont(this, m_cPosStatus.Base.FONT);
            }
            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_Activated(object sender, EventArgs e)
        {
            try
            {
                if (this.Tag.ToString() == "START")
                {
                    this.Tag = string.Empty;
                    this.lblMessage.Text = string.Empty;
                    this.Update();

                    switch (this.WorkType)
                    {
                        case PosKey.MENU_KEY.TABLE_BACKUP:
                            this.WorkResult = TableBackupProcess();
                            break;
                        case PosKey.MENU_KEY.TABLE_RESTORE:
                            this.WorkResult = TableRestorProcess();
                            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);
                this.DialogResult = System.Windows.Forms.DialogResult.Abort;
            }
            finally 
            {
                this.Close();
            }
        }

        private void Form_Closing(object sender, FormClosingEventArgs e)
        {
            this.WorkType = string.Empty; 

            UserLog.WriteLogFile(UserCom.LOG_IOS, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name
                                                , System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "."
                                                + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", "");
        }

        /// <summary>
        /// 테이블 백업
        /// </summary>
        /// <returns></returns>
        private string TableBackupProcess()
        {
            try
            {
                string ret = UserCom.RST_ERR;
                string msg = MessageManager.GetGuideMessage(POS_MESSAGE.GUIDE.MSG_0004);

                // 로컬저장
                SetMessage(msg + "\n(Save to local database)");
                ret = m_cTableSvr.TableMasterSave(this.FloorMaster, this.TableMaster);
                if (ret == UserCom.RST_ERR)
                {
                    WinManager.ErrorMessage(ret);
                    return UserCom.RST_ERR;
                }
                System.Threading.Thread.Sleep(1000);

                // 서버 백업 처리 
                SetMessage(msg + "\n(Backup to the server)");
                ret = m_cTableSvr.TableMasterBackup(this.FloorMaster, this.TableMaster);
                if (ret != UserCom.RST_OK)
                {
                    WinManager.ErrorMessage(ret);
                    return UserCom.RST_ERR;
                }

                WinManager.ConfirmMessage(POS_MESSAGE.ERROR.MSG_0519);

                return 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 UserCom.RST_ERR;
            }
        }

        /// <summary>
        /// 테이블 복원 
        /// </summary>
        /// <returns></returns>
        private string TableRestorProcess()
        {
            try
            {
                string ret = UserCom.RST_ERR;
                string msg = MessageManager.GetGuideMessage(POS_MESSAGE.GUIDE.MSG_0005);
                SetMessage(msg);

                // 복원 처리 
                SetMessage(msg + "\n(Restore data from the server)");
                ret = m_cTableSvr.TableMasterRestore();
                if (ret != UserCom.RST_OK)
                {
                    WinManager.ErrorMessage(ret);
                    return UserCom.RST_ERR;
                }
                System.Threading.Thread.Sleep(1000);

                // 층 마스터 로드
                SetMessage(msg + "\n(Reload the floor information)");
                if (LoadFloorMaster(false) == false)
                {
                    WinManager.ErrorMessage(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0522) + "\n" + "Reload floor master fails");
                    return UserCom.RST_ERR;
                }
                System.Threading.Thread.Sleep(1000);

                // 테이블 마스터 로드 
                SetMessage(msg + "\n(Reload the table information)");
                if (LoadTableMaster(false) == false)
                {
                    WinManager.ErrorMessage(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0522) + "\n" + "Reload table master fails");
                    return UserCom.RST_ERR;
                }

                return 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 UserCom.RST_ERR;
            }
        }

        private bool LoadFloorMaster(bool isShowMsg = true)
        {
            try
            {
                this.FloorMaster.Clear();

                DataTable dtData = null;
                string ret = m_cTableSvr.SelectFloor(new string[] { PosConst.QueryTagDef.QueryFloorDef.FLOOR_ALL_SEARCH, string.Empty }, out dtData);
                if (ret == UserCom.RST_IGNORE)
                {
                    if (isShowMsg) WinManager.ConfirmMessage(POS_MESSAGE.ERROR.MSG_0079);
                    return true;
                }
                if (ret != UserCom.RST_OK)
                {
                    if (isShowMsg) WinManager.ConfirmMessage(POS_MESSAGE.ERROR.MSG_0078);
                    return false;
                }

                foreach (DataRow dr in dtData.Rows)
                {
                    Column.MST_FLOOR.FLOOR_DATA cFloor = new Column.MST_FLOOR.FLOOR_DATA();
                    cFloor.FLOOR_CD = CmUtil.GetDataRowStr(dr, "FLOOR_CD");
                    cFloor.FLOOR_NM = CmUtil.GetDataRowStr(dr, "FLOOR_NM");
                    cFloor.UPD_DT = CmUtil.GetDataRowStr(dr, "UPD_DT");
                    cFloor.REG_DT = CmUtil.GetDataRowStr(dr, "REG_DT");
                    cFloor.STATUS = PosConst.DB_ROW_STATUS.NONE;

                    this.FloorMaster.Add(cFloor);
                }

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

        private bool LoadTableMaster(bool isShowMsg = true)
        {
            try
            {
                this.TableMaster.Clear();

                DataTable dtData = null;
                string ret = m_cTableSvr.SelectTable(new string[] { PosConst.QueryTagDef.QueryTableDef.TABLE_ALL_SEARCH }, out dtData);
                if (ret == UserCom.RST_IGNORE)
                {
                    if (isShowMsg) WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0495);
                    return true;
                }
                if (ret != UserCom.RST_OK)
                {
                    if (isShowMsg) WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0496);
                    return false;
                }

                foreach (DataRow dr in dtData.Rows)
                {
                    Column.MST_TABLE.TABLE_DATA cTable = new Column.MST_TABLE.TABLE_DATA();
                    m_cTableSvr.SetTableInfo(dr, ref cTable);

                    this.TableMaster.Add(cTable);
                }

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

        private void SetMessage(string msg)
        {
            this.lblMessage.Text = msg;
            this.lblMessage.Update();
        }
    }
}
