using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using System.Drawing;
using GatewayTool.Models;

namespace GatewayTool.UserControls
{
    public class CollectionEditorEx : CollectionEditor
    {
        private string propertyText = "";
        private bool isCopyExist = false;
        private Button copyButton;
        private ListBox listBox;
        private Label propertiesLabel;
        private PropertyGrid propertyBrowser;

        public CollectionEditorEx(Type type) : base(type)
        {
        }

        protected override CollectionForm CreateCollectionForm()
        {
            CollectionForm form = base.CreateCollectionForm();
            form.Font = new System.Drawing.Font("微软雅黑", 10.5f, System.Drawing.GraphicsUnit.Point);
            form.Shown += delegate
            {
                ShowDescription(form);
            };            

            var addButton = (ButtonBase)form.Controls.Find("addButton", true).First();
            var removeButton = (ButtonBase)form.Controls.Find("removeButton", true).First();
            var upButton = (ButtonBase)form.Controls.Find("upButton", true).First();
            var downButton = (ButtonBase)form.Controls.Find("downButton", true).First();
            listBox = (ListBox)form.Controls.Find("listbox", true).First();
            var cancelButton = (ButtonBase)form.Controls.Find("cancelButton", true).First();
            var okButton = (ButtonBase)form.Controls.Find("okButton", true).First();
            propertiesLabel = (Label)form.Controls.Find("propertiesLabel", true).First();
            var membersLabel = (Label)form.Controls.Find("membersLabel", true).First();
            propertyBrowser = (PropertyGrid)form.Controls.Find("propertyBrowser", true).First();
            propertyBrowser.ToolbarVisible = false;

            StringMsg strMsg = new FormBase().StrMsg;
            string name = form.Text.Split(' ')[0];
            form.Text = name + " " + strMsg.CollectionEditorTitle;
            membersLabel.Text = strMsg.CollectionEditorMember;
            addButton.Text = strMsg.CollectionEditorAdd;
            removeButton.Text = strMsg.CollectionEditorRemove;
            propertiesLabel.Text = strMsg.CollectionEditorProperty;
            propertyText = strMsg.CollectionEditorProperty;
            okButton.Text = strMsg.CollectionEditorOK;
            cancelButton.Text = strMsg.CollectionEditorCancel;

            listBox.SelectedIndexChanged += ListBox_SelectedIndexChanged;
            propertiesLabel.TextChanged += PropertiesLabel_TextChanged;
            okButton.Click += OkButton_Click;

            Control owner = removeButton.Parent;
            TableLayoutPanel pnl = owner as TableLayoutPanel;

            copyButton = new Button();
            copyButton.Name = "copyButton";
            copyButton.Anchor = AnchorStyles.Left | AnchorStyles.Right;
            copyButton.AutoSize = false;
            copyButton.Text = strMsg.CollectionEditorCopy;
            copyButton.Enabled = listBox.Items.Count > 0;
            pnl.Controls.Add(copyButton);
            copyButton.Width = (pnl.Width - addButton.Margin.Right * 2 - removeButton.Margin.Left * 2 - copyButton.Margin.Left * 2) / pnl.Controls.Count;
            copyButton.Height = addButton.Height;

            copyButton.Click += (sender, e) =>
            {
                isCopyExist = !isCopyExist;
                ChangeCopyButtonUI();

                //object selObj = listBox.SelectedItem;
                //string val = JsonConvert.SerializeObject(selObj);
                //Type type = selObj.GetType();
                //object newObj = JsonConvert.DeserializeObject(val);

                //System.ComponentModel.Design.CollectionEditor+CollectionEditorCollectionForm+ListItem

                //object selObj = propertyBrowser.SelectedObject;
                //listBox.Items.Add(selObj);
            };

            return form;
        }

        private void OkButton_Click(object sender, EventArgs e)
        {
            //object arr = listBox.DataSource;
            //for (int i = listBox.Items.Count - 1; i >= 0; i--)
            //{
            //    object obj = listBox.Items[i];
            //    if (!obj.Validate())
            //    {
            //        MessageBox.Show($"Item {i} has invalid value!","PropertyGrid");
            //        return;
            //    }
            //}
        }

        protected override object CreateInstance(Type itemType)
        {
            object newObj = base.CreateInstance(itemType);

            if (isCopyExist)
            {
                object selObj = propertyBrowser.SelectedObject;
                PropertyInfo[] newInfo = newObj.GetType().GetProperties();
                if (selObj != null)
                {
                    PropertyInfo[] selInfo = selObj.GetType().GetProperties();
                    foreach (PropertyInfo newP in newInfo)
                    {
                        foreach (PropertyInfo selP in selInfo)
                        {
                            if (newP.Name.Equals(selP.Name))
                            {
                                newP.SetValue(newObj, selP.GetValue(selObj));
                                break;
                            }
                        }
                    }
                }
            }

            return newObj;
        }

        private void PropertiesLabel_TextChanged(object sender, EventArgs e)
        {
            ChangePropertiesLabelText();
        }

        private void ChangeCopyButtonUI() 
        {
            copyButton.ForeColor = isCopyExist ? Color.Blue : Color.Black;
        }

        private void ChangePropertiesLabelText()
        {
            if (propertiesLabel.Text.Contains(" "))
            {
                propertiesLabel.Text = propertiesLabel.Text.Split(' ')[0] + " " + propertyText;
            }
            else
            {
                propertiesLabel.Text = propertyText;
            }
        }

        private void ListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            copyButton.Enabled = listBox.Items.Count > 0;
            ChangePropertiesLabelText();
        }

        void ShowDescription(Control control)
        {
            propertiesLabel.Text = propertyText;
            ChangeCopyButtonUI();

            PropertyGrid grid = control as PropertyGrid;
            if (grid != null) grid.HelpVisible = true;
            foreach (Control child in control.Controls)
            {
                ShowDescription(child);
            }
        }
    }
}