using CatLib;
using Highway.Assemble.common;
using System;
using System.Windows.Forms;

namespace HighWayAssemble
{
    public partial class SetCollectIDView : Form
    {
        ISoftInfo SoftInfo = null;
        //  IConfigInfo configInfo = null;
        public SetCollectIDView()
        {
            this.StartPosition = FormStartPosition.CenterScreen;
            FormBorderStyle = FormBorderStyle.FixedSingle;
            MaximizeBox = false; MinimizeBox = false;
            InitializeComponent();
            SoftInfo = App.Make<ISoftInfo>();
        }

        private void TextBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != 8 && !Char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            if (textBox_SoftID.Text.Length < 2)
            {
                MessageBox.Show("软件地址长度不足！");
                return;
            }
            SoftInfo.CollectInfo.collectID = textBox_SoftID.Text;
            // configInfo.CollectID = textBox_SoftID.Text;
            if (SetValue("CollectID", textBox_SoftID.Text))
            {
                // MessageBox.Show("软件地址设置完成！");
                Hide();
            }
        }
        /// <summary>
        /// 更新connectionStrings配置
        /// </summary>
        /// <param name="Key">索引</param>
        /// <param name="Value">值</param>
        public bool SetValue(string AppKey, string AppValue)
        {
            System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();
            xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");

            System.Xml.XmlNode xNode;
            System.Xml.XmlElement xElem1;
            System.Xml.XmlElement xElem2;
            xNode = xDoc.SelectSingleNode("//appSettings");

            xElem1 = (System.Xml.XmlElement)xNode.SelectSingleNode("//add[@key='" + AppKey + "']");
            if (xElem1 != null) xElem1.SetAttribute("value", AppValue);
            else
            {
                xElem2 = xDoc.CreateElement("add");
                xElem2.SetAttribute("key", AppKey);
                xElem2.SetAttribute("value", AppValue);
                xNode.AppendChild(xElem2);
            }
            xDoc.Save(System.Windows.Forms.Application.ExecutablePath + ".config");
            return true;
        }

        private void SetCollectIDView_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (textBox_SoftID.Text.Length < 1)
            {
                if (MessageBox.Show("确定不设置软件ID？", "系统提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    Hide();
                    //  Close();
                }
            }
        }
    }
}
