using Cosmos.BaseFrame;
using Cosmos.UserFrame;
using System;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using Cosmos.Common;

namespace DataBaseRestore
{
    public partial class frmMain : Form
    {

        #region Variable
        
        private readonly string CONFIG_FILE = "PosConfig.INI";
        private readonly string BACKUP_DIRECTORY = BaseCom.NxBackPath + PosConst.BACKUP_PATH.DB;

        protected DatabaseMssql m_cSqlDbService = null;
        
        //DB 접속 정보 변수
        string m_sLocalSource = "";
        string m_sLocalCatalog = "";
        string m_sLocalUserID = "";
        string m_sLocalPassword = "";
        
        private DataTable m_dtItemInit = null;

        private bool bIngFlag = false;

        #endregion Variable

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

        private void frmMain_Load(object sender, EventArgs e)
        {

            m_cSqlDbService = new DatabaseMssql();

            InitializeGrid();
            GetDatabaseConfig();
            GetFileList();
            txtPwd.Value = "";

            CreateDrectory();
            
        }


        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (bIngFlag == true)
            {
                e.Cancel = true;
            }
        }

        #endregion 생성자 & 소멸자


        #region 폼 컨트롤 초기화

        /// <summary>
        /// 그리드 초기화
        /// </summary>
        private void InitializeGrid()
        {
            try
            {
                //등록정보 표시 그리드
                grdFileList.CsmGridColumnHeadersVisible = true;           //DataGridView 자체의 컬럼 헤더 Visible 여부
                grdFileList.CsmGridColumnHeadersHeight = 39;              //DataGridView 자체의 컬럼 헤더 높이
                grdFileList.CsmGridRowsHeight = 40;
                grdFileList.CsmGridColumnCount = 4;                       //그리드의 컬럼수
                grdFileList.CsmGridShowPageRowsCount = 5;                 //그리드의 한 화면에 보이는 로우수
                grdFileList.CsmGridDefaultRowBackColor = Color.FromArgb(234, 234, 234); //그리드 홀수(Default)/짝수(Alternate)행의 배경색 지정
                grdFileList.CsmGridAlternateRowBackColor = Color.Ivory;
                grdFileList.CsmGridSetColumnWidth(new int[] { 50, 300, 330, 0 });   //컬럼넓이 지정(499)
                grdFileList.CsmGridAlignment(new int[] { 2, 0, 0, 0 });               //컬럼 정렬 0:왼쪽, 1:가운데, 2:오른쪽

                //각 컬럼별 이름 지정
                grdFileList.CsmGridColumnName(0, "Seq");
                grdFileList.CsmGridColumnName(1, "FileName");
                grdFileList.CsmGridColumnName(2, "CreateDateTime");
                grdFileList.CsmGridColumnName(3, "FullPath");
                
                //그리드 초기화 테이블
                m_dtItemInit = new DataTable("INIT");
                m_dtItemInit.Columns.Add(new DataColumn("Seq", typeof(string)));
                m_dtItemInit.Columns.Add(new DataColumn("FileName", typeof(string)));
                m_dtItemInit.Columns.Add(new DataColumn("CreateDateTime", typeof(string)));
                m_dtItemInit.Columns.Add(new DataColumn("FullPath", typeof(string)));
                
                m_dtItemInit.Clear();

            }
            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 + "()", ex.ToString());
            }
        }

        /// <summary>
        /// 디렉토리 생성
        /// </summary>
        private void CreateDrectory()
        {
            try
            {
                string sPath = BaseCom.NxBackPath + PosConst.BACKUP_PATH.DB;
                CmUtil.CreateDirectory(sPath);
            }
            catch (Exception)
            {

            }
        }

        #endregion 폼 컨트롤 초기화
        
        #region Control Event
        /// <summary>
        /// 종료
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        /// <summary>
        /// 기능키 처리
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnProc_Click(object sender, EventArgs e)
        {
            try
            {
                if ((Cosmos.UI.CsmButton)sender == btnUp)                               // 그리드 Up
                {
                    grdFileList.CsmGridScroll("UP");
                }
                else if ((Cosmos.UI.CsmButton)sender == btnDw)                          // 그리드 Down
                {
                    grdFileList.CsmGridScroll("DOWN");
                }
                else if ((Cosmos.UI.CsmButton)sender == btnBackup)                      // 백업
                {
                    SetBackupDatabase();
                    GetFileList();
                }
                else if ((Cosmos.UI.CsmButton)sender == btnRestore)                     // 복원
                {
                    SetRestoreDatabase();
                }
            }
            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 + "()", ex.ToString());
            }
        }

        #endregion Control Event

        #region User Method
        /// <summary>
        /// DB 정보 읽어 오기
        /// </summary>
        /// <returns></returns>
        private void GetDatabaseConfig()
        {
            try
            {
                CmMessage m_PosConfig = CmMessage.MakeMessageFromFile(BaseCom.NxIniPath + CONFIG_FILE);

                m_sLocalSource = UserLog.UserAES.StaticKeyDecrypt(CmUtil.StringNullEmpty(m_PosConfig.GetMessage("DATABASE").GetMessageValue("LocalSource")));
                m_sLocalCatalog = UserLog.UserAES.StaticKeyDecrypt(CmUtil.StringNullEmpty(m_PosConfig.GetMessage("DATABASE").GetMessageValue("LocalCatalog")));
                m_sLocalUserID = UserLog.UserAES.StaticKeyDecrypt(CmUtil.StringNullEmpty(m_PosConfig.GetMessage("DATABASE").GetMessageValue("LocalUserID")));
                m_sLocalPassword = UserLog.UserAES.StaticKeyDecrypt(CmUtil.StringNullEmpty(m_PosConfig.GetMessage("DATABASE").GetMessageValue("LocalPassword")));

                if (!(m_sLocalSource != "" && m_sLocalCatalog != "" && m_sLocalUserID != "" && m_sLocalPassword != ""))
                {
                    //에러
                    SetStatLabel(1, "Database Config File Read Error!");
                }
                
            }
            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 + "()", ex.ToString());
            }

        }
        /// <summary>
        /// 파일조회
        /// </summary>
        private void GetFileList()
        {

            int iSeq = 1;

            DataTable dt = m_dtItemInit.Clone();

            grdFileList.CsmGridClear();

            try
            {
                if (System.IO.Directory.Exists(BACKUP_DIRECTORY))
                {
                    System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(BACKUP_DIRECTORY);

                    foreach (var item in di.GetFiles().OrderByDescending(f => f.LastWriteTime))
                    {

                        if (item.Extension.ToUpper() == ".BAK")
                        {

                            DataRow dr = dt.NewRow();

                            dr["Seq"] = iSeq++;
                            dr["FileName"] = item.Name;
                            dr["CreateDateTime"] = item.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");
                            dr["FullPath"] = item.FullName;

                            dt.Rows.Add(dr);
                        }
                    }
                }

                if (dt == null || dt.Rows.Count == 0)
                {
                    grdFileList.CsmGridDataSource = m_dtItemInit;
                    SetStatLabel(1, "File Not Found!");
                }
                else
                {
                    m_dtItemInit = dt;
                    grdFileList.CsmGridDataSource = m_dtItemInit;
                    
                }

            }
            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 + "()", ex.ToString());
            }
        }

        /// <summary>
        /// 복원
        /// </summary>
        /// <returns></returns>
        private bool SetRestoreDatabase()
        {
            bool bRet = false;

            try
            {

                if (bIngFlag == true) return false;
                bIngFlag = true;

                SetStatLabel(0, "");

                m_cSqlDbService = new DatabaseMssql();

                //파일 선택 유무 체크
                if (grdFileList.CsmGridRowsCount == 0)
                {
                    SetStatLabel(1, "No File selected");
                    return false;
                }
                else if (txtPwd.Value == "")
                {
                    //비밀번호 입력 체크
                    SetStatLabel(1, "Please enter a password!");
                    return false;
                }
                else if (txtPwd.Value != DateTime.Now.ToString("ddMM"))
                {
                    SetStatLabel(1, "Password Error!");
                    return false;
                }

                int iRow = grdFileList.CsmGridSelectedRowIndex;

                string sFileName = m_dtItemInit.Rows[iRow]["FileName"].ToString();

                string[] sFileDiv = sFileName.Split(new char[] { '_', '.' });
                                
                //쿼리 생성
                string sSQL = string.Empty;

                if (sFileDiv.Equals("POSMST") == true)
                {
                    sSQL = " USE[master] ";
                    sSQL += " ALTER DATABASE [POSMST] ";
                    sSQL += " SET RESTRICTED_USER WITH ROLLBACK IMMEDIATE; ";
                    sSQL += " RESTORE DATABASE [POSMST] ";
                    sSQL += " FROM DISK = '{0}' ";
                    sSQL += " WITH REPLACE; ";

                    sSQL = string.Format(sSQL, grdFileList.CsmGridGetCell(grdFileList.CsmGridSelectedRowIndex, 3));

                    //실행
                    m_cSqlDbService.SetDBConnectionString(m_sLocalSource, m_sLocalCatalog, m_sLocalUserID, m_sLocalPassword);

                    int nRows = m_cSqlDbService.DBExecuteNonQuery(new string[] { sSQL }, false);
                    if (nRows > 0)
                    {
                        SetStatLabel(0, "DataBase(POSMST) Restore Success!");
                    }
                    else
                    {
                        SetStatLabel(1, "DataBase(POSMST) Restore Fail!");
                    }
                }
                else
                {
                    sSQL = " USE[master] ";
                    sSQL += " ALTER DATABASE [POSLOG] ";
                    sSQL += " SET RESTRICTED_USER WITH ROLLBACK IMMEDIATE; ";
                    sSQL += " RESTORE DATABASE [POSLOG] ";
                    sSQL += " FROM DISK = '{0}' ";
                    sSQL += " WITH REPLACE; ";

                    sSQL = string.Format(sSQL, grdFileList.CsmGridGetCell(grdFileList.CsmGridSelectedRowIndex, 3));

                    //실행
                    m_cSqlDbService.SetDBConnectionString(m_sLocalSource, m_sLocalCatalog, m_sLocalUserID, m_sLocalPassword);

                    int nRows = m_cSqlDbService.DBExecuteNonQuery(new string[] { sSQL }, false);
                    if (nRows > 0)
                    {
                        SetStatLabel(0, "DataBase(POSLOG) Restore Success!");
                    }
                    else
                    {
                        SetStatLabel(1, "DataBase(POSLOG) Restore Fail!");
                    }
                }

                //종료
                bIngFlag = false;
            }
            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 + "()", ex.ToString());
                bIngFlag = false;
            }

            return bRet;

        }

        /// <summary>
        /// 백업
        /// </summary>
        /// <returns></returns>
        private bool SetBackupDatabase()
        {
            bool bRet = false;

            try
            {
                if (bIngFlag == true) return false;
                bIngFlag = true;

                CreateDrectory();

                SetStatLabel(0, "");

                //쿼리 생성
                string sSQL = string.Empty;
                string sFullPath = string.Format("{0}{1}{2}", BACKUP_DIRECTORY, DateTime.Now.ToString("yyyyMMdd"), "_POSMST.BAK");
                
                sSQL += " USE[master] ";
                sSQL += " BACKUP DATABASE [POSMST] TO DISK = '{0}' WITH INIT; ";
                
                sSQL = string.Format(sSQL, sFullPath);
                

                //실행
                m_cSqlDbService.SetDBConnectionString(m_sLocalSource, m_sLocalCatalog, m_sLocalUserID, m_sLocalPassword);
                
                int nRows = m_cSqlDbService.DBExecuteNonQuery(new string[] { sSQL }, false);
                if (nRows > 0)
                {
                    SetStatLabel(0, "DataBase Backup Success!");
                }
                else
                {
                    SetStatLabel(1, "DataBase Backup Fail!");
                }

                //종료
                bIngFlag = false;
            }
            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 + "()", ex.ToString());
                bIngFlag = false;
            }

            return bRet;

        }



        /// <summary>
        /// 상태 메세지 셋팅
        /// </summary>
        /// <param name="iType">0:정상,1:에러,2:확인</param>
        /// <param name="sMsg">메세지</param>
        private void SetStatLabel(int iType, string sMsg)
        {
            try
            {
                if (iType == 1)
                {
                    lblStatMsg.BackColor = Color.Red;
                    lblStatMsg.ForeColor = Color.White;
                }
                else if (iType == 2)
                {
                    lblStatMsg.BackColor = Color.Blue;
                    lblStatMsg.ForeColor = Color.White;
                }
                else
                {
                    lblStatMsg.BackColor = Color.White;
                    lblStatMsg.ForeColor = Color.DimGray;
                }

                lblStatMsg.Text = sMsg;

                Application.DoEvents();
            }
            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 + "()", ex.ToString());
            }
        }

        #endregion User Method

    }
}
