using Tiobon.Core.OPS.Tool.OPS.Tool.Model;
using System;
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.Web.Script.Serialization;
using System.Windows.Forms;

namespace Tiobon.Core.OPS.Tool.OPS.Tool.View
{
    public partial class Frm_Conf : Form
    {
        public Func<Module, Module> End_Init;
        private Module module_conf;

        
        public Frm_Conf()
        {
            InitializeComponent();
        }

        public void GetConf(Module module)
        {
            Dictionary<string, string> pairs = new Dictionary<string, string>();
            for (int j = 0; j < module.keys.Count; j++)
            {
                pairs.Add(module.keys[j], module.values[j]);
            }
            module_conf = module;
            lbl_name.Text = module.Name;
            lbl_version.Text = module.version;
            txt_de.Text = module.Describe;
            int i = 0;
            this.Width = 400;
            foreach (var item in pairs)
            {
                Label label = new Label { Left = i % 2 == 0 ? 0 : 190, Top = i % 2 != 0 ? (i - 1) * 15 + 30 : i * 15 + 30, Text = item.Key+":" };
                label.Width = 50;
                TextBox textBox = new TextBox { Left = label.Left + label.Width, Top = label.Top - 5 , Width = 80, Name = item.Key, Text = item.Value.ToString().Replace("\n", "\r\n") };

                panel1.Controls.Add(label);
                panel1.Controls.Add(textBox);
                i++;
            }
            CenterToScreen();
        }


        private void button2_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var textBoxes = panel1.Controls.Cast<Control>().Where(item => item is TextBox).Cast<TextBox>().ToList();
            textBoxes.ForEach(item =>
            {
                var index = module_conf.keys.IndexOf(item.Name);
                module_conf.values[index] = item.Text;
            });
            JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
            string json = jsonSerializer.Serialize(module_conf);
            File.WriteAllText("Config/README.ihdis", json);
            DialogResult = DialogResult.OK;
            Close();
        }

        private void panel1_ControlAdded(object sender, ControlEventArgs e)
        {
            this.panel1.VerticalScroll.Enabled = true;
            this.panel1.VerticalScroll.Visible = true;
            this.panel1.Scroll += panel1_Scroll;
        }

        private void panel1_Scroll(object sender, ScrollEventArgs e)
        {
            this.panel1.VerticalScroll.Value = e.NewValue;
            panel1.Invalidate();//刷新panel
        }
    }
}
