using ProjectManagementSystem.Common.Core;
using ProjectManagementSystem.Common.Logger;
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 ProjectManagementSystem.UI
{
    public partial class DebugIOUI : UserControl, IDisplayUI
    {
        public DebugIOUI()
        {
            InitializeComponent();
        }

        public bool Init()
        {
            dataGridUI1.dataGridView1.CellClick += DataGridView1_CellClick;
            return true;
        }

        private void DataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            textBox1.Text = dataGridUI1.GetCurrentColValue("DeviceId");

            foreach (var item in panel2.Controls)
            {
                var checkBox = item as CheckBox;
                if(checkBox != null)
                {
                    checkBox.Checked = bool.Parse(dataGridUI1.GetCurrentColValue($"Y{checkBox.Text.Substring(1)}"));
                }
            }
            
        }

        public void UpdateDisplay()
        {
            if (!this.Visible) return;

            var dataList = DeviceControl.Instance.Communication.InfoIODictionary.Values.ToList();
            dataGridUI1.ShowDataGrid(dataList);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                int deviceId = int.Parse(textBox1.Text);

                ushort newOutput = 0;
                foreach (var item in panel2.Controls)
                {
                    var checkBox = item as CheckBox;
                    if (checkBox != null)
                    {
                        int index = int.Parse(checkBox.Text.Substring(1)) - 1;
                        if (checkBox.Checked)
                        {
                            newOutput = (ushort)(newOutput | (0x01 << index));
                        }
                        else
                        {
                            newOutput = (ushort)(newOutput & (ushort.MaxValue - (1 << index)));
                        }
                    }
                }

                DeviceControl.Instance.SetOutputIO(deviceId, newOutput);
            }
            catch (Exception ex)
            {
                CLog.Instance.SystemLog.WriteException("UI", ex);
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
