using System;

#if UNITY_WEBGL
using Seayoo.LitJson;
#else
using Newtonsoft.Json;
#endif

namespace Combo
{
    [System.Serializable]
    public abstract class Serializable
    {
        public string ToJson()
        {
            try
            {
#if UNITY_WEBGL
                return JsonMapper.ToJson(this);
#else
                return JsonConvert.SerializeObject(this);
#endif
            }
            catch (Exception _e)
            {
                throw new SerializationException(_e.Message, GetType().Name, "json");
            }
        }

        public static T FromJson<T>(string json) where T : Serializable
        {
            try
            {
#if UNITY_WEBGL
                return JsonMapper.ToObject<T>(json);
#else
                return JsonConvert.DeserializeObject<T>(json);
#endif
            }
            catch (Exception _e)
            {
                throw new SerializationException(_e.Message, json, typeof(T).Name);
            }

        }
    }

    public class SerializationException : Exception
    {
        override public string Source { get; set; }
        public string Destination { get; }

        public SerializationException(string message, string source, string destination)
            : base(message)
        {
            Source = source;
            Destination = destination;
        }

        public SerializationException(string message, string source, string destination, Exception innerException)
            : base(message, innerException)
        {
            Source = source;
            Destination = destination;
        }

        public override string ToString()
        {
            return $"SerializationException: {Message}\nSource: {Source}\nDestination Type: {Destination}\n{StackTrace}";
        }
    }
}