using System;
using _Core;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Seayoo.ComboSDK.Windows.Store.Networking.Model
{
    internal class RequestPayment
    {
        public class PaymentArgs : Serializable { }

        public class WeixinNativePaymentArgs : PaymentArgs
        {
            [JsonProperty("code_url")]
            public string codeUrl;
            [JsonProperty("time_expire")]
            public int timeExpire;
        }

        public class AlipayQrCodePaymentArgs : PaymentArgs
        {
            [JsonProperty("qr_code")]
            public string qrCode;
            [JsonProperty("time_expire")]
            public int timeExpire;
        }

        public class SeayooSandboxPaymentArgs : PaymentArgs
        {

        }

        public class Request : Serializable
        {
            [JsonProperty("order_token")]
            public string orderToken;

            [JsonProperty("payment_method")]
            public string paymentMethod;
        }

        public class Response : Serializable
        {
            [JsonProperty("order_id")]
            public string orderId;

            [JsonProperty("order_token")]
            public string orderToken;

            [JsonConverter(typeof(PaymentArgsConverter))]
            [JsonProperty("payment_args")]
            public PaymentArgs paymentArgs;
        }

        internal class PaymentArgsConverter : JsonConverter
        {
            public override bool CanConvert(Type objectType)
            {
                return objectType == typeof(PaymentArgs);
            }

            public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
            {
                JObject obj = JObject.Load(reader);

                if (obj["code_url"] != null)
                {
                    return obj.ToObject<WeixinNativePaymentArgs>(serializer);
                }
                else if (obj["qr_code"] != null)
                {
                    return obj.ToObject<AlipayQrCodePaymentArgs>(serializer);
                }
                else if(!obj.HasValues)
                {
                    return obj.ToObject<SeayooSandboxPaymentArgs>(serializer);
                }
                else
                {
                    throw new JsonSerializationException("Unknown subclass of PaymentArgs");
                }
            }

            public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
            {
                JToken t = JToken.FromObject(value);
                t.WriteTo(writer);
            }
        }
    }
}
