using System;
using System.Globalization;
using System.Linq;

namespace InABox.WPF;

public class TimeSpanToStringConverter : AbstractConverter<TimeSpan,String>
{
    public TimeSpanToStringConverter(string? format)
    {
        Format = format ?? "HH:mm";
    }

    public string Format { get; set; }
    
    public override string Convert(TimeSpan value)
    {
        try
        {
            var result = string.IsNullOrWhiteSpace(Format) || string.Equals(Format, "hh:mm")|| string.Equals(Format, "HH:mm")
                ? Math.Truncate(value.TotalHours).ToString("#00") + ":" + value.Minutes.ToString("D2")
                : string.Format("{0:" + Format.Replace(":", "\\:") + "}", value);
            return result;
        }
        catch (Exception e)
        {
            return value.ToString("c");
        }

    }

    public override TimeSpan Deconvert(string value)
    {
        if (string.IsNullOrWhiteSpace(Format) || string.Equals(Format, "hh:mm") || string.Equals(Format, "HH:mm"))
        {
            var comps = value.Split(':');
            if (comps.Length == 2)
            {
                if (int.TryParse(comps[0], out int hrs) && int.TryParse(comps[1], out int mins))
                    return new TimeSpan(hrs, mins, 0);
            }
        }
        else
        {
            if (TimeSpan.TryParseExact(value, Format, CultureInfo.InvariantCulture, TimeSpanStyles.None,  out TimeSpan result))
                return result;

        }
        return TimeSpan.Zero;
    }
}
