using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Globalization;


namespace Fuel.Payment.Core.Models
{
    public class PosJsonDateConverter : DateTimeConverterBase
    {
        List<string> timeFormats = new List<string>{
            "M/d/yyyy h:mm:ss",
            "M/d/yyyy h:mm:ss tt",
            "yyyy/M/d h:mm:ss",
            "yyyy/M/d h:mm:ss tt",
            "yyyy/MM/dd h:mm:ss",
            "yyyy-MM-dd HH:mm:ss",
            "yyyy-MM-dd HH:mm:ss tt",
            "yyyy-MM-dd HH:mm:ss fff",
            "yyyy-MM-dd HH:mm:ss ffffff"};

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            DateTime result;
            try
            {
                foreach (var format in timeFormats)
                {
                    if (DateTime.TryParseExact(reader.Value.ToString(), format, CultureInfo.InvariantCulture, DateTimeStyles.None, out result))
                    {
                        result = DateTime.ParseExact(reader.Value.ToString(), format, null);
                        return result;
                    }
                }
                return result = DateTime.Parse(reader.Value.ToString());
            }
            catch (FormatException f)
            {
                return default(DateTime);
            }
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            writer.WriteValue(((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss.fff"));
        }
    }
}
