using InABox.Core;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace InABox.DynamicGrid
{
    public class DFBooleanControl : DynamicFormFieldControl<DFLayoutBooleanField, DFLayoutBooleanFieldProperties, bool, bool?>
    {
        private IOptionControl OptionControl = null!; // Late-initialised

        protected override FrameworkElement Create()
        {
            var options = new[] { Field.Properties.TrueValue, Field.Properties.FalseValue };
            switch (Field.Properties.Type)
            {
                case DesignBooleanFieldType.Buttons:
                    return SetControl(new ButtonsOptionControl(options, ChangeField));
                case DesignBooleanFieldType.ComboBox:
                    return SetControl(new ComboBoxOptionControl(options, ChangeField));
            }
            return SetControl(new CheckBoxOptionControl(Field.Properties.TrueValue, Field.Properties.FalseValue, ChangeField));
        }

        private T SetControl<T>(T value)
            where T : FrameworkElement, IOptionControl
        {
            OptionControl = value;
            return value;
        }

        public override bool? GetSerializedValue()
        {
            return GetValue();
        }

        public override void SetSerializedValue(bool? value)
        {
            SetValue(value ?? false);
        }

        public override bool GetValue() => OptionControl.GetValue() == Field.Properties.TrueValue;

        public override void SetValue(bool value) => OptionControl.SetValue(value ? Field.Properties.TrueValue : Field.Properties.FalseValue);

        protected override bool IsEmpty() => Field.Properties.Type switch
        {
            DesignBooleanFieldType.Checkbox => GetValue() != true,
            _ => OptionControl.IsEmpty()
        };
    }
}
