namespace InABox.Core
{
    public enum DesignBooleanFieldType
    {
        Checkbox,
        ComboBox,
        Buttons
    }

    public class DFLayoutBooleanFieldProperties : DFLayoutFieldProperties<bool, bool?>
    {
        
        [EditorSequence(-995)]
        [CheckBoxEditor]
        public override bool Default { get; set; }
        
        [EnumLookupEditor(typeof(DesignBooleanFieldType))]
        [EditorSequence(1)]
        public DesignBooleanFieldType Type { get; set; }

        [TextBoxEditor]
        [EditorSequence(2)]
        public string TrueValue { get; set; }

        [TextBoxEditor]
        [EditorSequence(3)]
        public string FalseValue { get; set; }

        protected override void LoadProperties()
        {
            base.LoadProperties();
            Type = GetProperty("Type", DesignBooleanFieldType.Checkbox);
            TrueValue = GetProperty("TrueValue", "True");
            FalseValue = GetProperty("FalseValue", "False");
        }

        protected override void SaveProperties()
        {
            base.SaveProperties();
            SetProperty("Type", Type);
            SetProperty("TrueValue", TrueValue);
            SetProperty("FalseValue", FalseValue);
        }

        public override string FormatValue(bool? value)
        {
            return value == true ? TrueValue : FalseValue;
        }

        public override bool GetValue(bool? value)
        {
            return value ?? Default;
        }

        public override bool? DeserializeValue(DFLoadStorageEntry entry)
        {
            var value = entry.GetValue();
            if (value is bool b)
                return b;
            if (bool.TryParse(value as string, out var result))
                return result;
            if (value is string str)
            {
                if (str == TrueValue)
                    return true;
                if (str == FalseValue)
                    return false;
                return null;
            }
            return null;
        }

        public override void SerializeValue(DFSaveStorageEntry entry, bool? value)
        {
            if(value == true)
            {
                entry.SetValue(TrueValue);
            }
            else if (value == false)
            {
                entry.SetValue(FalseValue);
            }
        }
    }
}