using Newtonsoft.Json.Linq;
using System;

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

        public string Format { get; set; }

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

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

        public override void SerializeValue(DFSaveStorageEntry entry, double? value)
        {
            if(value != null)
            {
                entry.SetValue(value);
            }
        }

        public override double? DeserializeValue(DFLoadStorageEntry entry)
        {
            var value = entry.GetValue();
            if (value is double d)
                return d;
            if (value != null && value.GetType().IsNumeric())
            {
                try
                {
                    return Convert.ToDouble(value);
                }
                catch (Exception)
                {
                    return null;
                }
            }
            if (double.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);
        }
    }
}