using Newtonsoft.Json;
using System;

namespace EVCB_OCPP.Packet20.Utilites
{
    public class UTCDateTimeConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(DateTime);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            DateTime? timevalue = null;
            if (reader.Value != null)
            {
                DateTime date = ((DateTime)reader.Value).ToLocalTime();
                timevalue = new DateTime(date.Year, date.Month, date.Day, date.TimeOfDay.Hours, date.TimeOfDay.Minutes, date.TimeOfDay.Seconds, 000);
            }
            return timevalue;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var date = (DateTime)value;
            string timevalue = date.ToUniversalTime().ToString("yyyy-MM-ddT") + date.ToUniversalTime().TimeOfDay.ToString(@"hh\:mm\:ss\.fff") + "Z";
            writer.WriteValue(timevalue);
        }
    }
}
