using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using InABox.Core;

namespace InABox.DynamicGrid
{

    public class ScriptEditorControl : DynamicEditorControl<string, ScriptEditor>
    {
        
        static ScriptEditorControl()
        {
            //DynamicEditorControlFactory.Register<ScriptEditorControl, ScriptEditor>();
        }
        
        private Button Editor;

        private string script = "";
        public ScriptEditorControl()
        {
            SyntaxLanguage = SyntaxLanguage.CSharp;
        }
        public SyntaxLanguage SyntaxLanguage { get; set; }

        public event OnScriptEditorClickedEvent OnEditorClicked;

        public override void Configure()
        {
            SyntaxLanguage = EditorDefinition.SyntaxLanguage;
        }

        protected override FrameworkElement CreateEditor()
        {
            Editor = new Button
            {
                Content = "Edit..",
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment = VerticalAlignment.Stretch,
                VerticalContentAlignment = VerticalAlignment.Center,
                Width = 50
            };
            Editor.Click += Editor_Click;

            return Editor;
        }

        private void Editor_Click(object sender, RoutedEventArgs e)
        {
            if (EditorDefinition.GetType() == typeof(ScriptEditor))
            {
                CheckTemplateEditor();
            }
            else
                ShowEditor();
        }

        private void CheckTemplateEditor()
        {
            var edt = EditorDefinition as ScriptEditor;

            if (edt.Type == ScriptEditorType.TemplateEditor)
                edt.InvokeEvent();

            else
                ShowEditor();
        }

        private void ShowEditor()
        {
            var editor = new ScriptEditorWindow(script, SyntaxLanguage);
            if (editor.ShowDialog() == true)
            {
                script = editor.Script;
                CheckChanged();
            }
        }


        public override int DesiredHeight()
        {
            return 25;
        }

        public override int DesiredWidth()
        {
            return 100;
        }

        protected override string RetrieveValue()
        {
            return script;
        }

        protected override void UpdateValue(string value)
        {
            script = value.NotWhiteSpaceOr("");
        }

        public override void SetFocus()
        {
            Editor.Focus();
        }

        public override void SetColor(Color color)
        {
            //Editor.Background = new SolidColorBrush(color);
        }
    }
}