using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Media;
using InABox.Core;
using Syncfusion.Windows.Shared;
using Syncfusion.Windows.Tools.Controls;

namespace InABox.DynamicGrid
{
    public class CheckListBoxEditorControl : DynamicEditorControl<Dictionary<string, bool>>, ILookupEditorControl
    {
        private SolidColorBrush _color;

        private Dictionary<object, string> _lookups;

        private Type _realtype;
        private Dictionary<string, bool> _value;
        private bool bLoading;

        private CheckListBox Editor;

        public override void Configure()
        {
            base.Configure();
            Editor.IsEnabled = false;
            Editor.Background = Brushes.WhiteSmoke;
            OnDefineLookups?.Invoke(this);
        }


        public override int DesiredHeight()
        {
            return 300;
        }

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

        public Dictionary<string, string> OtherColumns { get; set; }

        public event OnDefineLookup OnDefineLookups;

        public event OnLookupsDefined OnLookupsDefined;

        public void LoadLookups(CoreTable otherfields)
        {
            _lookups = new Dictionary<object, string>();
            foreach (var row in otherfields.Rows)
                _lookups[row[ColumnName]] = row["Display"].ToString();
            SetupCheckListBox();
            OnLookupsDefined(this);
        }

        protected override FrameworkElement CreateEditor()
        {
            MinHeight = 50;
            Editor = new CheckListBox
            {
                VerticalAlignment = VerticalAlignment.Stretch,
                VerticalContentAlignment = VerticalAlignment.Top,
                HorizontalAlignment = HorizontalAlignment.Stretch,
                //SelectedItemBackground = Brushes.Transparent,
                //Foreground = Brushes.Black
                DisplayMemberPath = "Value",
                SelectedValuePath = "Key"
            };
            SkinStorage.SetVisualStyle(Editor, "Metro");
            Editor.SelectionChanged += (o, e) =>
            {
                if (!bLoading)
                    CheckChanged();
            };
            return Editor;
        }

        public override int DesiredWidth()
        {
            return 150;
        }

        protected override Dictionary<string, bool> RetrieveValue()
        {
            _value = Activator.CreateInstance(_realtype) as Dictionary<string, bool>;
            foreach (KeyValuePair<object, string> pair in Editor.Items)
                _value[pair.Key.ToString()] = Editor.SelectedItems.Contains(pair);
            return _value;
        }

        protected override void UpdateValue(Dictionary<string, bool> value)
        {
            _realtype = value.GetType();
            _value = value;
            SetupCheckListBox();
        }

        public override void SetColor(Color color)
        {
            if (Editor.IsEnabled)
                Editor.Background = new SolidColorBrush(color);
            else
                _color = new SolidColorBrush(color);
        }


        private void SetupCheckListBox()
        {
            if (_lookups == null || _value == null || bLoading)
                return;
            bLoading = true;
            var sorted = _lookups.ToList();
            sorted.Sort((pair1, pair2) => pair1.Value.ToString().CompareTo(pair2.Value.ToString()));
            Editor.ItemsSource = sorted;

            if (_value != null)
            {
                foreach (var pair in sorted)
                {
                    var key = pair.Key.ToString();
                    if (_value.ContainsKey(key))
                    {
                        if (_value[key])
                            //Logger.Send(LogType.Information, "", String.Format("- Enabled: {0} / {1}", key, pair.Value));
                            Editor.SelectedItems.Add(pair);
                        //else
                        //Logger.Send(LogType.Information, "", String.Format("- Disabled: {0} / {1}", key, pair.Value));
                    }
                    else
                    {
                        //Logger.Send(LogType.Information, "",String.Format("- New Token: {0} / {1}",key,pair.Value));
                        Editor.SelectedItems.Add(pair);
                    }
                }

                Editor.IsEnabled = true;
                if (_color != null)
                    Editor.Background = _color;
            }

            bLoading = false;
        }
    }
}