using System;

namespace InABox.Core
{
    public class DFLayoutTimeFieldProperties : DFLayoutFieldProperties<TimeSpan>
    {
        public DFLayoutTimeFieldProperties()
        {
            Format = "hh:mm";
        }

        public string Format { get; set; }

        public override string FormatValue(object value)
        {
            var time = new TimeSpan();
            if (value != null)
            {
                if (value is TimeSpan)
                    time = (TimeSpan)value;
                else if (value is string)
                    TimeSpan.TryParse(value as string, out time);
            }

            return string.IsNullOrWhiteSpace(Format) || string.Equals(Format, "hh:mm")
                ? Math.Truncate(time.TotalHours).ToString("#00") + ":" + time.Minutes.ToString("D2")
                : string.Format("{0:" + Format.Replace(":", "\\:") + "}", time);
        }

        public override object ParseValue(object value)
        {
            if (value is TimeSpan)
                return value;
            if (TimeSpan.TryParse(value as string, out var result))
                return result;
            return false;
        }

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

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