using DevExpress.XtraEditors;
using LFP_Manager.DataStructure;
using LFP_Manager.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LFP_Manager.Controls
{
    public delegate void PrintOptionEvent(object sender, int id);

    public partial class ucEventLog : DevExpress.XtraEditors.XtraUserControl
    {
        #region VARIABLES
        CommConfig Config;
        DataTable AlarmHistory = new DataTable();

        private int print_id = 0;

        public event PrintOptionEvent OnPrintOption = null;

        #endregion

        #region CONSTRUCTORS
        public ucEventLog()
        {
            InitializeComponent();
        }
        #endregion

        #region PUBLIC UPDATE

        public void UpdateConfig(CommConfig aConfig)
        {
            this.Config = aConfig;
        }

        public void EventUpdate(int id, string aEvent)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new MethodInvoker(delegate ()
                {
                    if (chkPacketLog.Checked)
                        PrintMsg(id, aEvent);
                }));
            }
            else
            {
                if (chkPacketLog.Checked)
                    PrintMsg(id, aEvent);
            }
        }

        private void PrintMsg(int id, string msg)
        {
            if ((print_id == 0) || (print_id == id))
            {
                meDataLog.Text = msg + meDataLog.Text;
            }
        }

        public void ErrorUpdate(int id, string aEvent)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new MethodInvoker(delegate ()
                {
                    //if (cbPacketLog.Checked)
                    meDataLog.Text = aEvent + meDataLog.Text;
                }));
            }
            else
            {
                //if (cbPacketLog.Checked)
                meDataLog.Text = aEvent + meDataLog.Text;
            }
        }

        public void AlarmHistoryUpdate1(DataTable aAlarmHistory)
        {
            if (aAlarmHistory != null)
            {
                AlarmHistory = aAlarmHistory;
                if (InvokeRequired)
                {
                    Invoke(new MethodInvoker(delegate ()
                    {
                        GvAlarmHistory.DataSource = AlarmHistory;
                        GvAlarmHistory.Columns["create_date"].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss";
                        GvAlarmHistory.DefaultCellStyle.NullValue = "null";
                        GvAlarmHistory.DefaultCellStyle.WrapMode = DataGridViewTriState.True;

                        GvAlarmHistory.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
                        GvAlarmHistory.AllowUserToAddRows = false;

                        // 예: Id, ct_no 칼럼 숨기기
                        csDbUtils.HideColumns(GvAlarmHistory, "Id", "alarm_code", "alarm_status");
                    }));
                }
                else
                {
                    GvAlarmHistory.DataSource = AlarmHistory;
                    GvAlarmHistory.Columns["create_date"].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss";
                    GvAlarmHistory.DefaultCellStyle.NullValue = "null";
                    GvAlarmHistory.DefaultCellStyle.WrapMode = DataGridViewTriState.True;

                    GvAlarmHistory.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
                    GvAlarmHistory.AllowUserToAddRows = false;

                    // 예: Id, ct_no 칼럼 숨기기
                    csDbUtils.HideColumns(GvAlarmHistory, "Id", "alarm_code", "alarm_status");
                }
            }
        }

        #endregion

        #region ENVENT

        private void btnLogClear_Click(object sender, EventArgs e)
        {
            meDataLog.Text = "";
        }

        private async void BtnRefresh_Click(object sender, EventArgs e)
        {
            if (Config == null) return;

            BtnRefresh.Enabled = false;
            Cursor = Cursors.WaitCursor;

            try
            {
                // DB 조회는 백그라운드에서
                var now = DateTime.Now;
                var table = await Task.Run(() => csDbUtils.GetBmsAlarmDataByDataTable(Config, now, ""));

                // UI 바인딩
                Action bind = () =>
                {
                    AlarmHistory = table ?? new DataTable();
                    GvAlarmHistory.DataSource = AlarmHistory;
                };
                if (InvokeRequired)
                    BeginInvoke(new MethodInvoker(() => bind())); // ← 새 MethodInvoker 생성
                else
                    bind();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                Cursor = Cursors.Default;
                BtnRefresh.Enabled = true;
            }
        }

        private void CbPrintID_SelectedValueChanged(object sender, EventArgs e)
        {
            try
            {
                print_id = Convert.ToInt32(CbPrintID.SelectedItem.ToString());

                OnPrintOption?.Invoke(this, print_id);
            }
            catch (Exception ex)
            {
                _ = MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        #region HELPER FUNCTIONS
        public void AlarmHistoryUpdate(DataTable aAlarmHistory)
        {
            if (InvokeRequired)
            {
                Invoke(new MethodInvoker(delegate ()
                {
                    try
                    {
                        AlarmHistory = csDbUtils.GetBmsAlarmDataByDataTable(Config, DateTime.Now, "");

                        AlarmHistoryUpdate(AlarmHistory);
                    }
                    catch (Exception ex)
                    {
                    }
                }));
            }
            else
            {
                try
                {
                    AlarmHistory = csDbUtils.GetBmsAlarmDataByDataTable(Config, DateTime.Now, "");

                    AlarmHistoryUpdate(AlarmHistory);
                }
                catch (Exception ex)
                {
                }
            }
        }
        #endregion
    }
}
