using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema;
using System;

namespace InABox.Core
{
    public class DFLayoutIntegerFieldProperties : DFLayoutFieldProperties<int, int?>
    {
        
        [EditorSequence(-995)]
        [IntegerEditor]
        public override int Default { get; set; }
        
        public DFLayoutIntegerFieldProperties()
        {
            Format = "";
        }

        public string Format { get; set; }

        public override string FormatValue(int? value)
        {
            return string.Format("{0" + (string.IsNullOrWhiteSpace(Format) ? "" : ":" + Format) + "}", value);
        }

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

        public override void SerializeValue(DFSaveStorageEntry entry, int? value)
        {
            if (value.HasValue)
            {
                entry.SetValue(value);
            }
        }

        public override int? DeserializeValue(DFLoadStorageEntry entry)
        {
            var value = entry.GetValue();
            if (value is null)
                return null;

            if (value.GetType().IsNumeric())
            {
                return Convert.ToInt32(value);
            }
            if (int.TryParse(value as string, out var result))
                return result;
            return null;
        }

        protected override void LoadProperties()
        {
            base.LoadProperties();
            Format = GetProperty("Format", Format);
        }

        protected override void SaveProperties()
        {
            base.SaveProperties();
            SetProperty("Format", Format);
        }
    }
}