using Newtonsoft.Json.Linq;
using ProductionControl.Utils;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ProductionControl
{
    public partial class FrmCMDProcess : Form
    {
        ArrayList cmdList=new ArrayList();
        private int currKey;
        public FrmCMDProcess()
        {
            InitializeComponent();
            this.uiIOCardDev0.GetParamsEvent = save;
        }
      
        private void initData()
        {
            cmdList = Utils.EnumUtil.GetArrayList<CMDName>();
            cobCMDProcess.DisplayMember = "Value";
            cobCMDProcess.ValueMember = "Key";
            cobCMDProcess.DataSource = cmdList;
            cobCMDProcess.SelectedIndex = 0;
        }
        private void FrmSetParams_Load(object sender, EventArgs e)
        {
            try
            {
                uiIOCardDev0.init();
                initData(); 
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Close();
            }
        }
        private void cobCMDProcess_SelectedIndexChanged(object sender, EventArgs e)
        {
            currKey = (int)cobCMDProcess.SelectedValue;
            if (Config.CMDProcess.ContainsKey((CMDName)currKey))
                this.uiIOCardDev0.setParamsData(Config.CMDProcess[(CMDName)currKey].ToString()); 
        }
        private void save(string json)
        {
            Config.CMDProcess[(CMDName)currKey] = JObject.Parse(json);
            File.WriteAllText(Application.StartupPath + "\\CMDProcess\\" + currKey + ".json", json);
            MessageBox.Show("保存成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void tsbtnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void FrmCMDProcess_FormClosing(object sender, FormClosingEventArgs e)
        {
            string lsBasePath = Application.StartupPath + "\\CMDProcess\\";
            foreach (DictionaryEntry item in cmdList)
            {
                if(!File.Exists(lsBasePath+item.Key+".json"))
                {
                    MessageBox.Show($"[{item.Value}] 指令未设置，请先把系统指令集全部设置完成！", "失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    e.Cancel = true;
                    return;
                }
            }
        }
    }
}
