using CsvHelper;
using CsvHelper.Configuration;
using CsvHelper.TypeConversion;
using InABox.Core;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace InABox.Poster.Timberline
{
    public class TimberlinePosterStringConverter : DefaultTypeConverter
    {
        public int MaxLength { get; set; }

        public TimberlinePosterStringConverter(int maxLength)
        {
            MaxLength = maxLength;
        }

        public override object? ConvertFromString(string? text, IReaderRow row, MemberMapData memberMapData)
        {
            return text;
        }

        public override string? ConvertToString(object? value, IWriterRow row, MemberMapData memberMapData)
        {
            return ConvertString(value, MaxLength);
        }

        public static string ConvertString(object? value, int maxLength)
        {
            var str = value?.ToString() ?? "";
            if (str.Length > maxLength)
            {
                str = str[..maxLength];
            }
            str = str.ReplaceLineEndings(" ");
            return str;
        }

    }

    public class TimberlinePosterDateConverter : DefaultTypeConverter
    {
        public override object? ConvertFromString(string? text, IReaderRow row, MemberMapData memberMapData)
        {
            if (text.IsNullOrWhiteSpace())
            {
                return DateTime.MinValue;
            }
            return DateTime.Parse(text);
        }

        public override string? ConvertToString(object? value, IWriterRow row, MemberMapData memberMapData)
        {
            if(value is DateTime date && date == DateTime.MinValue)
            {
                return "";
            }
            else
            {
                return string.Format("{0:dd/MM/yyyy}", value);
            }
        }
    }
}
