using Newtonsoft.Json;
using Pilz.Cryptography;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Pilz.Json.Converters
{
    public class SecureStringJsonConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return typeof(SecureString).IsAssignableFrom(objectType);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var idString = serializer.Deserialize<string>(reader);
            SecureString  id;

            if (existingValue is SecureString)
            {
                id = (SecureString)existingValue;
                id.EncryptedValue = idString;
            }
            else
                id = new SecureString(idString, true);

            return id;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            serializer.Serialize(writer, ((SecureString)value).EncryptedValue);
        }
    }
}
