﻿using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Nest;

namespace Quest.Common.JSON
{
    public class GeoCoordinateConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(GeoCoordinate);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.StartObject)
            {
                var dict = new Dictionary<string, double>();
                serializer.Populate(reader, dict);
                return new GeoCoordinate(dict["lat"], dict["lon"]);
            }

            return null;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var name = value as GeoCoordinate;
            writer.WriteStartObject();
            writer.WritePropertyName("lat");
            writer.WriteValue(name.Latitude);
            writer.WritePropertyName("lon");
            writer.WriteValue(name.Longitude);
            writer.WriteEndObject();
        }
    }
}