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

namespace Cosmos.Win
{
    public partial class frmDatabaseBackup : Form
    {
        private SManager sManager = new SManager();                   // 이 객체를 통해 업무 Service 호출
        private PosStatus m_cPosStatus = null;
        private DeviceStatus m_cDevStatus = null;                     //디바이스 관리
        private StateServer StateObject = (StateServer)StateServer.GetInstance();
        
        public frmDatabaseBackup()
        {
            InitializeComponent();

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

            m_cPosStatus = (PosStatus)StateObject.POS;
        }

        private void frmDatabaseBackup_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>
        private void InitControl()
        {
            this.BackgroundImage = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.POP_MSGBOX);

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

            //btnOk.Visible = false;

            //btnOk.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0009);    //확인

            lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0746);
            lblMessage.Text = MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0432);

            this.TopMost = true;

            tmrStart.Enabled = true;
        }
            
        private void frmDatabaseBackup_Activated(object sender, EventArgs e)
        {
            
        }

        private void frmDatabaseBackup_Deactivate(object sender, EventArgs e)
        {
            
        }

        private void frmDatabaseBackup_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);
        }
        
        private void btnOk_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void tmrStart_Tick(object sender, EventArgs e)
        {
            tmrStart.Stop();
            tmrStart.Enabled = false;
            try
            {

                //#20171013 DB 축소 기능 start
                //SetShrinkDatabase();    //디비축소
                //#20171013 DB 축소 기능 end

                SetBackupDatabase();
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_IOS, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                 System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", "");
            }
            finally
            {
                this.Close();
            }
        }

        #region 데이터 베이스 백업
        /// <summary>
        /// 데이터 베이스 백업
        /// </summary>
        /// <returns></returns>
        private bool SetBackupDatabase()
        {
            bool bRet = false;

            try
            {
                IDatabaseSQL m_cSqlDbService = (IDatabaseSQL)sManager.InitServiceInstance(ServiceLists.AGENT_DATABASE.DLL, ServiceLists.AGENT_DATABASE.DATABASE_MSSQL);

                if (m_cSqlDbService != null)
                {
                    //쿼리 생성
                    string sSQL = string.Empty;
                    string sPath = BaseCom.NxBackPath + PosConst.BACKUP_PATH.DB;
                    string sFullPath = "";

                    CmUtil.CreateDirectory(sPath);

                    sFullPath = string.Format("{0}{1}{2}", sPath, 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_cPosStatus.Base.LocalDbSource, m_cPosStatus.Base.LocalDbCatalog, m_cPosStatus.Base.LocalDbUserID, m_cPosStatus.Base.LocalDbPassword);

                    int nRows = m_cSqlDbService.DBExecuteNonQuery(new string[] { sSQL }, false);
                    if (nRows > 0)
                    {
                        UserLog.WriteLogFile(UserCom.LOG_DEBUG, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                            System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", "DataBase(POSMST) Backup Success!");
                    }
                    else
                    {
                        UserLog.WriteLogFile(UserCom.LOG_DEBUG, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                            System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", "DataBase(POSMST) Backup Fail!");
                    }

                    sFullPath = string.Format("{0}{1}{2}", sPath, DateTime.Now.ToString("yyyyMMdd"), "_POSLOG.BAK");

                    sSQL = string.Empty;
                    sSQL += " USE[master] ";
                    sSQL += " BACKUP DATABASE [POSLOG] TO DISK = '{0}' WITH INIT; ";

                    sSQL = string.Format(sSQL, sFullPath);

                    m_cSqlDbService.SetDBConnectionString(m_cPosStatus.Base.LocalDbSource, m_cPosStatus.Base.LocalDbCatalog, m_cPosStatus.Base.LocalDbUserID, m_cPosStatus.Base.LocalDbPassword);

                    nRows = m_cSqlDbService.DBExecuteNonQuery(new string[] { sSQL }, false);
                    if (nRows > 0)
                    {
                        UserLog.WriteLogFile(UserCom.LOG_DEBUG, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                            System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", "DataBase(POSLOG) Backup Success!");
                    }
                    else
                    {
                        UserLog.WriteLogFile(UserCom.LOG_DEBUG, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                            System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", "DataBase(POSLOG) Backup Fail!");
                    }
                }

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

            return bRet;

        }
        #endregion 데이터 베이스 백업

        //#20171013 DB 축소 기능 start
        //마감 후 DB 백업 전 실행
        #region 데이터 축소
        /// <summary>
        /// 데이터 베이스 백업
        /// </summary>
        /// <returns></returns>
        private bool SetShrinkDatabase()
        {
            bool bRet = false;

            try
            {
                IDatabaseSQL m_cSqlDbService = (IDatabaseSQL)sManager.InitServiceInstance(ServiceLists.AGENT_DATABASE.DLL, ServiceLists.AGENT_DATABASE.DATABASE_MSSQL);

                if (m_cSqlDbService != null)
                {
                    //쿼리 생성
                    string sSQL = string.Empty;

                    sSQL += " DBCC SHRINKDATABASE(POSMST, 10) ";

                    sSQL = string.Format(sSQL);

                    m_cSqlDbService.SetDBConnectionString(m_cPosStatus.Base.LocalDbSource, m_cPosStatus.Base.LocalDbCatalog, m_cPosStatus.Base.LocalDbUserID, m_cPosStatus.Base.LocalDbPassword);

                    int nRows = m_cSqlDbService.DBExecuteNonQuery(new string[] { sSQL }, false);
                    if (nRows > 0)
                    {
                        UserLog.WriteLogFile(UserCom.LOG_DEBUG, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                            System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", "DataBase(POSMST) Shrink Success!");
                    }
                    else
                    {
                        UserLog.WriteLogFile(UserCom.LOG_DEBUG, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                            System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", "DataBase(POSMST) Shrink Fail!");
                    }

                    sSQL = string.Empty;
                    sSQL += " DBCC SHRINKDATABASE(POSLOG, 10) ";

                    sSQL = string.Format(sSQL);

                    m_cSqlDbService.SetDBConnectionString(m_cPosStatus.Base.LocalDbSource, m_cPosStatus.Base.LocalDbCatalog, m_cPosStatus.Base.LocalDbUserID, m_cPosStatus.Base.LocalDbPassword);

                    nRows = m_cSqlDbService.DBExecuteNonQuery(new string[] { sSQL }, false);
                    if (nRows > 0)
                    {
                        UserLog.WriteLogFile(UserCom.LOG_DEBUG, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                            System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", "DataBase(POSLOG) Shrink Success!");
                    }
                    else
                    {
                        UserLog.WriteLogFile(UserCom.LOG_DEBUG, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                            System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", "DataBase(POSLOG) Shrink Fail!");
                    }
                }

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

            return bRet;

        }
        #endregion 데이터 축소
        //#20171013 DB 축소 기능 end 

    }
}
