using System.Text;
using Guru.LitJson;
using UnityEngine;
using UnityEngine.Networking;

namespace Guru
{
    public class AppleOrderRequest : RequestBase
    {
        public int orderType;
        public string productId;
        public string receipt;
        public int level;

        public AppleOrderRequest(){}
        public AppleOrderRequest(int orderType, string productId, string receipt, int level)
        {
            this.orderType = orderType;
            this.productId = productId;
            this.receipt = receipt;
            this.level = level;
        }

        protected override string RequestURL => IPMConfig.IPM_URL + "order/api/v1/orders/ios";
        protected override UnityWebRequest CreateRequest()
        {
            AppleOrderData appleOrderData = new AppleOrderData(receipt, level);
            this.Log($"send orderData:{appleOrderData}");
            var request = new UnityWebRequest(RequestURL, "POST");
            request.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(JsonMapper.ToJson(appleOrderData)));
            request.downloadHandler = new DownloadHandlerBuffer();
            request.SetRequestHeader(IPMConfig.Header_Param_APPID, IPMConfig.IPM_X_APP_ID);
            request.SetRequestHeader(IPMConfig.Header_Param_UID, IPMConfig.IPM_UID);
            request.SetRequestHeader(IPMConfig.Header_Param_ACCESS_TOKEN, IPMConfig.IPM_TOKEN);
            request.SetRequestHeader(IPMConfig.Header_Param_ContentType, IPMConfig.Header_Value_ContentType);
            return request;
        }

        protected override void RequestSuccessCallBack(string response)
        {
            ResponseData<OrderResponse> responseData = JsonUtility.FromJson<ResponseData<OrderResponse>>(response);
            if (responseData != null && responseData.data != null)
            {
                // Analytics.Tch001IAPRev(responseData.data.usdPrice);
                double usdPrice = responseData.data.usdPrice;
                Analytics.Tch001IAPRev(usdPrice);
                Analytics.Tch02IAPRev(usdPrice);
                AdjustService.TrackIAPPurchase(usdPrice, productId);
                Analytics.IAPPurchase(usdPrice, productId);
            }
        }
    }
}