using System;
using System.Globalization;
using InABox.Core;

namespace InABox.WPF;

public class DateTimeToStringConverter : AbstractConverter<DateTime,String>
{
    public string Format { get; }
        
    public DateTimeToStringConverter(string? format = null)
    {
        Format = format ?? "dd/MM/yyyy HH:mm:ss";
    }
    
    public override string Convert(DateTime value)
    {
        if (value is DateTime datetime && !datetime.IsEmpty())
            return String.Format("{0:" + Format + "}", datetime);
        return "";
    }

    public override DateTime Deconvert(string value)
    {
        if (String.IsNullOrWhiteSpace(value))
            return DateTime.MinValue;
                
        if (DateTime.TryParseExact(value, Format, CultureInfo.InvariantCulture, DateTimeStyles.None,
                out DateTime result))
            return result;
        return DateTime.MinValue;
    }
}