using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing.Design;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using PXP.Crawler.API.Designers.Property.Forms;
using PXP.Crawler.API.Utils;

namespace PXP.Crawler.API.Designers.Property
{
    public class CodePropertyEditor : UITypeEditor
    {
        private IWindowsFormsEditorService editorService;

        public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
        {
            return UITypeEditorEditStyle.Modal;
        }

        public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
        {
            if (provider != null)
            {
                editorService =
                    provider.GetService(
                    typeof(IWindowsFormsEditorService))
                    as IWindowsFormsEditorService;
            }



            if (editorService != null)
            {
                PropertyCodeEditXtraForm pcForm = new PropertyCodeEditXtraForm();
                string ccode = Null.StringFromDBNull(value, "", true);

                if (ccode.Length == 0)
                {
                    PropertyInfo prInfo = context.Instance.GetType().GetProperty(context.PropertyDescriptor.Name);
                    if (prInfo != null)
                    {
                        CodePropertyDefault cpDef = prInfo.GetCustomAttribute<CodePropertyDefault>();
                        if (cpDef != null)
                        {
                            ccode = cpDef.Code;
                        }
                    }
                }

                pcForm.codeScintilla.Text = ccode;

                if (editorService.ShowDialog(pcForm) == DialogResult.OK)
                {
                    value = pcForm.codeScintilla.Text;
                }
            }

            return value;
        }
    }

    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
    public class CodePropertyDefault : Attribute
    {
        private string code;
        public CodePropertyDefault(string defaultCode)
        {
            code = defaultCode;
        }

        public string Code
        {
            get { return code; }
        }
    }
}
