using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraGrid.Views.Grid;
using SystemX.Product.ALIS.UI.View.InfoList;
using System.Data.SqlClient;
using SystemX.Product.ALIS.Interface;
using static SystemX.Product.ALIS.UI.View.ViewCfg;
using static SystemX.Net.Platform.Common.Util.LogMessage;
using static SystemX.Product.ALIS.UI.Commons;

namespace SystemX.Product.ALIS.UI.View.Base
{
    public partial class UcBaseView : UserControl, IUserControlSubscribe
    {
        /// <summary>
        /// IUserControlSubscribe
        /// </summary>
        /// <param name="CurrentAccessLevel"></param>
        /// <param name="bLoginState"></param>
        public void SetLoginStateNotice(LoginAccessLevel CurrentAccessLevel, bool bLoginState)
        {
            bool bSetState = ((CurrentAccessLevel == ThisAccessLevel) && (bLoginState == true)) ? true : false;

            ViewLoginState = bSetState;

            WizardCancelEvent?.Invoke(bSetState, null);

            this.Invoke((MethodInvoker)delegate ()
            {
                if (bSetState)
                {
                    layoutControlItemDataMod.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
                    layoutControlItemModelMod.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
                }
                else
                {
                    layoutControlItemDataMod.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                    layoutControlItemModelMod.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                }
            });
        }

        /// <summary>
        /// IUserControlSubscribe - GoToFindTestListFileFocus
        /// </summary>
        /// <param name="nTestListFileNo"></param>
        public void GoToFindTestListFileFocus(int nTestListFileNo)
        {
            ;//
        }

        /// <summary>
        /// IUserControlSubscribe - GoToFindParentFocus
        /// </summary>
        /// <param name="nParentNo"></param>
        public void GoToFindVariantFocus(int nVariantNo)
        {
            ;//
        }


        /// <summary>
        /// IUserControlSubscribe
        /// </summary>
        public void RefreshDataView()
        {
            ViewList();
        }


        private void EventClear(object obj)
        {
            if (WizardCancelEvent != null)
            {
                foreach (Delegate d in WizardCancelEvent?.GetInvocationList())
                {
                    if (d.Target.GetType() == obj.GetType())
                        WizardCancelEvent -= (EventHandler)d;
                }
            }
        }

        public event EventHandler WizardCancelEvent;

        public int AbsoluteIndexRow { get; set; }

        public string AbsoluteUniqueNo { get; set; }

        public string AbsoluteHostName { get; set; }

        //public int AbsoluteIndexCol { get; set; }


        IDataController ctrlDB;


        private DataSet ds = new DataSet();
        private DataTable dt = new DataTable();

        eSelectType SelectOpenType { get; set; }

        string strSelectTable;

        public LoginAccessLevel ThisAccessLevel { get; private set; }

        public bool ViewLoginState { private set; get; }

        public UcBaseView(eSelectType SelType, IDataController ctrlDB, LoginAccessLevel MakeAccessLevel, bool bLoginState = false)
        {
            InitializeComponent();

            ThisAccessLevel = MakeAccessLevel;

            ViewLoginState = bLoginState;

            if (ViewLoginState)
                layoutControlItemDataMod.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;

            this.ctrlDB = ctrlDB;

            SelectOpenType = SelType;

            strSelectTable = "";

            ViewList();

            AbsoluteIndexRow = -1;
            //AbsoluteIndexCol = -1;

            AbsoluteUniqueNo = "";

            simpleButtonRegister1.Text = "Register " + SelectOpenType.ToString();
        }

        public void CreateInfo(eSelectType SelType)
        {
        }

        private void ViewList(string strSetTableName = "")
        {
            eDbTableList selTable = eDbTableList.NONE;

            string vTblName = string.Empty;

            if (strSelectTable.Length <= 0)
                return;

            if (strSetTableName.Length > 0)
                vTblName = strSetTableName;
            else
                vTblName = strSelectTable;

            if (Enum.TryParse<eDbTableList>(vTblName, out selTable))
            {
                ViewgridControl.BeginUpdate();

                ViewgridControl.DataSource = null;

                gridHistView.RefreshData();

                ViewgridControl.DataSource = ctrlDB.GetTable(selTable);
                //ViewgridControl.DataMember = vTblName;
                ViewgridControl.Views[0].PopulateColumns();

                gridHistView.BestFitColumns();

                ViewgridControl.EndUpdate();
            }
        }

        private void simpleButtonRegister1_Click(object sender, EventArgs e)
        {
            DialogResult getResult = new DialogResult();
            getResult = DialogResult.None;
            switch (SelectOpenType)
            {        
                default:
                    break;
            }
            try
            {
                if (getResult == DialogResult.OK)
                {
                    int EffectRows = ctrlDB.GetConnSqlCmd().ExecuteNonQuery();
                }
            }
            catch (Exception ex)
            {
                MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @" simpleButtonRegister1_Click() Error. " + ex.Message, ConsoleColor.Red, LogMessageLevel.FATAL);
            }

            ViewList();
        }

        private void simpleButtonModify1_Click(object sender, EventArgs e)
        {
            if (AbsoluteIndexRow < 0 || AbsoluteUniqueNo.Length < 0)
            {
                MessageBox.Show("Click the [No] column of the row you want.", strSelectTable, MessageBoxButtons.OK, MessageBoxIcon.Warning);

                return;
            }

            DialogResult getResult = new DialogResult();
            getResult = DialogResult.None;
            switch (SelectOpenType)
            {  
                default:
                    break;
            }

            try
            {
                if (getResult == DialogResult.OK)
                {
                    int EffectRows = ctrlDB.GetConnSqlCmd().ExecuteNonQuery();
                }
            }
            catch (Exception ex)
            {
                MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @" simpleButtonModify1_Click() Error. " + ex.Message, ConsoleColor.Red, LogMessageLevel.FATAL);
            }

            ViewList();
        }

        private void contextMenuStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            ToolStripItem tsp = e.ClickedItem;

            string strTitle = SelectOpenType.ToString();

            if (AbsoluteIndexRow >= 0 && AbsoluteUniqueNo.Length > 0)
            {
                if (MessageBox.Show("Are you sure you want to delete the " + strTitle + " [" + AbsoluteHostName + "] information?", strTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    switch (SelectOpenType)
                    {
                        default:
                            break;
                    }

                    try
                    {
                        int EffectRows = ctrlDB.GetConnSqlCmd().ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {
                        MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @" contextMenuStrip_ItemClicked() Error. " + ex.Message, ConsoleColor.Red, LogMessageLevel.FATAL);
                    }

                    ViewList();
                }
            }
        }

        private void ClearListSelect()
        {
            simpleLabelItemSelectRow.Text = "-";

            AbsoluteIndexRow = -1;

            AbsoluteUniqueNo = "";
        }

        private void gridHistView_RowClick(object sender, RowClickEventArgs e)
        {
            object objHandle = null;

            try
            {
                objHandle = gridHistView.GetFocusedRowCellValue("No");
            }
            catch
            {
                objHandle = null;
            }
            finally
            {
                AbsoluteIndexRow = e.RowHandle;

                simpleLabelItemSelectRow.Text = "Select Row : " + (e.RowHandle + 1).ToString();

                if (objHandle != null)
                {
                    try
                    {
                        string strNumber = gridHistView.GetFocusedRowCellValue("No").ToString();

                        AbsoluteUniqueNo = strNumber;

                        CreateInfo(SelectOpenType);
                    }
                    catch
                    {
                        ClearListSelect();
                    }
                }
                else
                {
                    ClearListSelect();
                }
            }
        }

        private void gridHistView_RowCellClick(object sender, RowCellClickEventArgs e)
        {
            /*if (e.Column.FieldName.Equals("No"))
            {
                simpleLabelItemSelectRow.Text = "Select Row : " + (e.RowHandle + 1).ToString();
                simpleLabelItemSelectCol.Text = "Select Col : " + (e.Column.AbsoluteIndex + 1).ToString();

                AbsoluteIndexRow = e.RowHandle;
                AbsoluteIndexCol = e.Column.AbsoluteIndex;

                string strNumber = gridHistView.GetFocusedRowCellValue("No").ToString();

                AbsoluteUniqueNo = strNumber;

                CreateInfo(SelectOpenType);
            }
            else
            {
                simpleLabelItemSelectRow.Text = "-";
                simpleLabelItemSelectCol.Text = "-";

                AbsoluteIndexRow = -1;
                AbsoluteIndexCol = -1;

                AbsoluteUniqueNo = "";
            }*/
        }

        private void simpleButtonViewList_Click(object sender, EventArgs e)
        {
            ViewList();
        }

        private void simpleButtonDataMod_Click(object sender, EventArgs e)
        {
            if (layoutControlItemModelMod.Visibility == DevExpress.XtraLayout.Utils.LayoutVisibility.Never)
            {
                layoutControlItemModelMod.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
            }
            else
                layoutControlItemModelMod.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
        }

        private void contextMenuStrip_Opening(object sender, CancelEventArgs e)
        {
            if ((ThisAccessLevel & LoginAccessLevel.None) == LoginAccessLevel.None)
                e.Cancel = true;
        }
    }
}
