using System;
using System.Collections.Generic;
using Cute;
using Cute.Payment;
using UnityEngine;
using Wizard;

public class PaymentImpl : PaymentBase, IPaymentCallback, IPaymentCommonCallback
{
	public enum PaymentOriginalScreen
	{
		SHOP_PLUS,
		MYPAGE,
		NONE
	}

	public List<string> ProductIdList;

	public List<string> IdList;

	public Dictionary<string, string> ProductPriceList;

	public Dictionary<string, string> FormatProductPriceList;

	public Dictionary<string, string> ProductNameList;

	public Dictionary<string, string> ProductTextList;

	public Dictionary<string, string> ProductPurchaseLimitList;

	public Dictionary<string, string> ProductPurchaseNumberList;

	public Dictionary<string, string> ProductCsvIdList;

	public Dictionary<string, string> ProductImageNameList;

	public Dictionary<string, bool> ProductIsSpecialShop;

	public Dictionary<string, int> ProductCurrentPurchaseCount;

	public Dictionary<string, int> ProductPurchaseLimitCount;

	public Dictionary<string, string> ProductEndTime;

	private string lastErrorMethod;

	private string lastErrorMessage;

	private long lastLogTimeTicks = DateTime.Now.Ticks;

	private int sameLogCount;

	public PaymentOriginalScreen PaymentFromScreen;

	public List<PaymentSkuInfo> skuInfos;

	public string selectedStoreProductId;

	public List<PaymentPurchase> lastSucceededPurchases = new List<PaymentPurchase>();

	public int resumePurchaseTransactionCount;

	public bool inProcessingResumePurchaseTransaction;

	public bool inProcessingPurchaseTransaction;

	public bool isPaymentListErrorDialogOpen;

	private bool _receivePaymentSuccess;

	private bool _receivePaymentCancel;

	private static PaymentImpl instance;

	private bool isCountTime;

	private bool isCountTimeForProductListInit;

	private float timer;

	public string StoreProductCountryCode { get; private set; }

	public string StoreProductCurrencyCode { get; private set; }

	public bool IsRefundedReceipt { get; private set; }

	public PaymentUI paymentUI { get; private set; }

	public event Action ProductListSucceeded;

	public event Action ProductListFailed;

	public event Action<string> FinishFailureEvent;

	public event Action<NetworkTask.ResultCode> purchaseFinishSuccessEvent;

	public event Action<NetworkTask.ResultCode> purchaseFinishHttpErrorEvent;

	public event Action<int> purchaseFinishResultCodeErrorEvent;

	public event Action purchaseRetryResultEvent;

	public event Action ConsumePurchaseSucceeded;

	private void Awake()
	{
		if (paymentUI == null)
		{
			paymentUI = new PaymentUI();
		}
	}

	private void Update()
	{
		if (isCountTime)
		{
			checkTimeOut();
		}
	}

	public static PaymentImpl GetInstance()
	{
		if (instance == null)
		{
			GameObject obj = new GameObject("PaymentImpl");
			UnityEngine.Object.DontDestroyOnLoad(obj);
			instance = obj.AddComponent<PaymentImpl>();
		}
		return instance;
	}

	private void OnItemListFailure(NetworkTask.ResultCode code)
	{
		Debug.LogError("OnItemListFailure" + code);
		Debug.LogError("プロダクトIDリストリクエストが失敗しました。やり直してください。");
	}

	private void OnItemListResultCodeError(int code)
	{
		Debug.LogError("OnItemListResultCodeError" + code);
		this.ProductListFailed.Call();
	}

	private void OnFinishSuccess(NetworkTask.ResultCode code)
	{
		string[] array = new string[lastSucceededPurchases.Count];
		for (int i = 0; i < lastSucceededPurchases.Count; i++)
		{
			array[i] = lastSucceededPurchases[i].getProductId();
		}
		string orderId = ((lastSucceededPurchases.Count > 0) ? lastSucceededPurchases[0].getOrderId() : "");
		Payment.consumePurchase(array, orderId);
	}

	private void OnFinishFailure(NetworkTask.ResultCode code)
	{
		paymentUI.StopLoading();
		Debug.LogError("OnFinishFailure:" + code);
		if (this.purchaseFinishHttpErrorEvent != null)
		{
			this.purchaseFinishHttpErrorEvent(code);
		}
		inProcessingPurchaseTransaction = false;
	}

	private void OnFinishResultCodeError(int resultCode)
	{
		paymentUI.StopLoading();
		Debug.LogError("OnFinishResultCodeError" + resultCode);
		Debug.LogError("チェック不正です。");
		if (this.purchaseFinishResultCodeErrorEvent != null)
		{
			this.purchaseFinishResultCodeErrorEvent(resultCode);
		}
		inProcessingPurchaseTransaction = false;
	}

	public void OnPaymentCancelByRefundWarningDialog()
	{
		inProcessingPurchaseTransaction = false;
	}

	public void evInitializeSucceeded()
	{
		paymentUI.StopLoading();
		Payment.getProductList(ProductIdList.ToArray());
	}

	public void OnInitializeSucceeded()
	{
		evInitializeSucceeded();
	}

	public void evInitializeFailed(string error)
	{
		paymentUI.StopLoading();
		if (BattleManagerBase.GetIns() == null)
		{
			sendPaymentErrorLog("evInitializeFailed", error);
			this.ProductListFailed.Call();
		}
	}

	public void OnInitializeFailed(int errorCode, string errorMessage)
	{
		evInitializeFailed(errorMessage);
	}

	public void evPurchaseSucceeded(PaymentPurchase purchase)
	{
		if (BattleManagerBase.GetIns() == null)
		{
			paymentUI.StopLoading();
			_receivePaymentSuccess = true;
			lastSucceededPurchases.Add(purchase);
			selectedStoreProductId = purchase.getProductId();
		}
	}

	public void OnPurchaseFailed(string error)
	{
		evPurchaseFailed(error);
	}

	public void OnPurchaseFailed(int errorCode, string errorMessage)
	{
		evPurchaseFailed(errorCode + ":" + errorMessage);
	}

	public void evPurchaseFailed(string error)
	{
		if (BattleManagerBase.GetIns() != null)
		{
			return;
		}
		paymentUI.StopLoading();
		string message = paymentUI.GetText("Shop_0072");
		if (_receivePaymentCancel)
		{
			return;
		}
		_receivePaymentCancel = true;
		PaymentCancelTask paymentCancelTask = new PaymentCancelTask();
		paymentCancelTask.SetParameter(getSkuInfo(GetInstance().selectedStoreProductId), error);
		StartCoroutine(Toolbox.NetworkManager.Connect(paymentCancelTask, delegate
		{
			if (!error.Contains("Received a pending purchase of SKU:") && !_receivePaymentSuccess)
			{
				if (this.FinishFailureEvent != null)
				{
					this.FinishFailureEvent(message);
				}
				else
				{
					paymentUI.PurchaseFailed();
				}
			}
		}, delegate
		{
		}, delegate(int code)
		{
			Debug.LogError("OnPurchaseFailedCancelTaskResultCodeError" + code);
		}));
		inProcessingPurchaseTransaction = false;
	}

	public void OnPurchaseCancelled(string productId, string price, string currencyCode)
	{
		evPurchaseCancelled("");
	}

	public void evPurchaseCancelled(string error)
	{
		paymentUI.StopLoading();
		string message = paymentUI.GetText("Shop_0073");
		PaymentCancelTask paymentCancelTask = new PaymentCancelTask();
		paymentCancelTask.SetParameter(getSkuInfo(GetInstance().selectedStoreProductId), error);
		StartCoroutine(Toolbox.NetworkManager.Connect(paymentCancelTask, delegate
		{
			if (this.FinishFailureEvent != null)
			{
				this.FinishFailureEvent(message);
			}
			else
			{
				paymentUI.PurchaseCancelled();
			}
		}, delegate
		{
		}, delegate(int code)
		{
			Debug.LogError("OnCancelResultCodeError" + code);
		}));
		inProcessingPurchaseTransaction = false;
	}

	public void OnGetProductListSucceeded(List<PaymentSkuInfo> productInfo, bool waitUnfinishedTransaction)
	{
		evGetProductListSucceeded(productInfo);
	}

	public void evGetProductListSucceeded(List<PaymentSkuInfo> infos)
	{
		skuInfos = infos;
		string text = "アイテムリストを取得しました" + Environment.NewLine;
		ProductPriceList.Clear();
		FormatProductPriceList.Clear();
		int count = infos.Count;
		for (int i = 0; i < count; i++)
		{
			ProductPriceList.Add(infos[i].productId, infos[i].price);
			FormatProductPriceList.Add(infos[i].productId, infos[i].formattedPrice);
			StoreProductCountryCode = infos[i].currencyCode;
			StoreProductCurrencyCode = infos[i].currencyCode;
			if (!string.IsNullOrEmpty(StoreProductCountryCode))
			{
				PlayerPrefsWrapper.SetValue(PlayerPrefsWrapper.CURRENT_REGION_CODE, StoreProductCountryCode);
			}
			text = text + " " + infos[i].title + " : " + infos[i].formattedPrice + Environment.NewLine;
		}
		if (!inProcessingResumePurchaseTransaction)
		{
			paymentUI.StopLoading();
		}
	}

	public void OnGetProductListFailed(int errorCode, string errorMessage)
	{
		evGetProductListFailed(errorCode + ":" + errorMessage);
	}

	public void evGetProductListFailed(string error)
	{
		paymentUI.StopLoading();
		if (BattleManagerBase.GetIns() == null)
		{
			sendPaymentErrorLog("evGetProductListFailed", error);
			this.ProductListFailed.Call();
			inProcessingPurchaseTransaction = false;
		}
	}

	public void OnConsumePurchaseSucceeded()
	{
		evConsumePurchaseSucceeded();
	}

	public void evConsumePurchaseSucceeded()
	{
		paymentUI.StopLoading();
		lastSucceededPurchases.Clear();
		this.ConsumePurchaseSucceeded.Call();
		inProcessingPurchaseTransaction = false;
	}

	public void OnConsumePurchaseFailed(int errorCode, string errorMessage)
	{
		evConsumePurchaseFailed(errorCode + ":" + errorMessage);
	}

	public void evConsumePurchaseFailed(string error)
	{
		paymentUI.StopLoading();
		sendPaymentErrorLog("evConsumePurchaseFailed", error);
		inProcessingPurchaseTransaction = false;
	}

	public void evConsumePurchaseSucceedediOS()
	{
	}

	public void TryToShowBuyResultPopUp(int amount, int sum, bool isRefundedReceipt = false)
	{
		IsRefundedReceipt = isRefundedReceipt;
		if (this.purchaseFinishSuccessEvent != null)
		{
			this.purchaseFinishSuccessEvent(NetworkTask.ResultCode.Success);
			return;
		}
		string value = "";
		ProductNameList.TryGetValue(selectedStoreProductId, out value);
		paymentUI.PurchaseFinished(value, amount, sum, isRefundedReceipt);
	}

	public void TryToShowBuyResultPopUpSecond(bool isRefundedReceipt = false)
	{
		IsRefundedReceipt = isRefundedReceipt;
		string value = "";
		ProductNameList.TryGetValue(selectedStoreProductId, out value);
		paymentUI.PurchaseFinished(value, 0, 0, isRefundedReceipt);
		if (this.purchaseRetryResultEvent != null)
		{
			this.purchaseRetryResultEvent();
		}
	}

	public override void purchaceStart(string storeProductId, bool isFromAlert = false)
	{
		if (inProcessingPurchaseTransaction)
		{
			return;
		}
		inProcessingPurchaseTransaction = true;
		string message = "";
		if (false)
		{
			sendPaymentErrorLog("purchaceStart", message);
			if (this.FinishFailureEvent != null)
			{
				string text = paymentUI.GetText("Shop_0072");
				this.FinishFailureEvent(string.Format(text, resumePurchaseTransactionCount));
			}
			else
			{
				paymentUI.PurchaseFailed();
			}
			inProcessingPurchaseTransaction = false;
			return;
		}
		_receivePaymentSuccess = false;
		_receivePaymentCancel = false;
		bool isAlertOn = PlayerPrefsWrapper.GetBool(PlayerPrefsWrapper.PURCHASE_ALERT);
		if (!isFromAlert)
		{
			IsAlertAgree = false;
		}
		PaymentStartTask task = new PaymentStartTask();
		task.SetParameter(getSkuInfo(storeProductId), IsAlertAgree, isAlertOn);
		task.SkipAllCuteResultCodeCheckErrorPopup();
		StartCoroutine(Toolbox.NetworkManager.Connect(task, delegate
		{
			Payment.purchaseProduct(storeProductId, task.NeedRefundWarningType);
		}, delegate
		{
			inProcessingPurchaseTransaction = false;
		}, delegate(int code)
		{
			inProcessingPurchaseTransaction = false;
			if (code == 329)
			{
				if (isAlertOn)
				{
					SystemText systemText = Data.SystemText;
					DialogBase dialogBase = UIManager.GetInstance().CreateDialogClose();
					dialogBase.SetSize(DialogBase.Size.S);
					dialogBase.SetTitleLabel(systemText.Get("ErrorHeader_0329"));
					dialogBase.SetText(systemText.Get("Error_0329"));
					dialogBase.SetButtonText(systemText.Get("Shop_0082"));
					dialogBase.SetFadeButtonEnabled(flag: false);
					dialogBase.SetButtonLayout(DialogBase.ButtonLayout.BlueBtn_CancelBtn);
					dialogBase.SetPanelDepth(6000);
					dialogBase.SetPanelSortingOrder(2);
					dialogBase.SetButtonDelegate(new EventDelegate(delegate
					{
						CallPaymentStartFromAlert(storeProductId);
					}));
				}
				else
				{
					CallPaymentStartFromAlert(storeProductId);
				}
			}
			else
			{
				Toolbox.NetworkManager.NetworkUI.OpenCloseOnlyErrorPopUp(code);
			}
		}));
		selectedStoreProductId = storeProductId;
	}

	public void initialize()
	{
		if (!inProcessingPurchaseTransaction)
		{
			this.ProductListSucceeded = null;
			this.ProductListFailed = null;
			this.FinishFailureEvent = null;
			this.purchaseFinishSuccessEvent = null;
			this.purchaseFinishHttpErrorEvent = null;
			this.purchaseFinishResultCodeErrorEvent = null;
			this.purchaseRetryResultEvent = null;
			this.ConsumePurchaseSucceeded = null;
			ProductIdList = new List<string>();
			IdList = new List<string>();
			ProductNameList = new Dictionary<string, string>();
			ProductPriceList = new Dictionary<string, string>();
			FormatProductPriceList = new Dictionary<string, string>();
			ProductTextList = new Dictionary<string, string>();
			ProductPurchaseLimitList = new Dictionary<string, string>();
			ProductPurchaseNumberList = new Dictionary<string, string>();
			ProductCsvIdList = new Dictionary<string, string>();
			ProductImageNameList = new Dictionary<string, string>();
			ProductIsSpecialShop = new Dictionary<string, bool>();
			ProductCurrentPurchaseCount = new Dictionary<string, int>();
			ProductPurchaseLimitCount = new Dictionary<string, int>();
			lastSucceededPurchases = new List<PaymentPurchase>();
			ProductEndTime = new Dictionary<string, string>();
			PaymentItemListTask task = new PaymentItemListTask();
			StartCoroutine(Toolbox.NetworkManager.Connect(task, delegate
			{
				Payment.initialize(GetInstance(), "");
			}, OnItemListFailure, OnItemListResultCodeError));
		}
	}

	public void finalize()
	{
		inProcessingPurchaseTransaction = false;
		inProcessingResumePurchaseTransaction = false;
		resumePurchaseTransactionCount = 0;
		this.ProductListSucceeded = null;
		this.ProductListFailed = null;
		this.FinishFailureEvent = null;
		this.purchaseFinishSuccessEvent = null;
		this.purchaseFinishHttpErrorEvent = null;
		this.purchaseFinishResultCodeErrorEvent = null;
		this.purchaseRetryResultEvent = null;
		this.ConsumePurchaseSucceeded = null;
		Payment.finalize();
	}

	public void StartTimeCount(bool forProductListInit = false)
	{
		isCountTime = true;
		isCountTimeForProductListInit = forProductListInit;
	}

	public void StopTimeCount()
	{
		isCountTime = false;
		timer = 0f;
	}

	private void checkTimeOut()
	{
		timer += Time.deltaTime;
		if (!(timer >= 30f))
		{
			return;
		}
		timer = 0f;
		paymentUI.StopLoading();
		if (isCountTimeForProductListInit)
		{
			if (PaymentFromScreen == PaymentOriginalScreen.SHOP_PLUS)
			{
				paymentUI.ProductListInitTimeOut();
			}
		}
		else
		{
			paymentUI.PurchaseTimeOut();
		}
	}

	public PaymentSkuInfo getSkuInfo(PaymentPurchase purchase)
	{
		return skuInfos.Find((PaymentSkuInfo x) => x.productId == purchase.getProductId());
	}

	public PaymentSkuInfo getSkuInfo(string productId)
	{
		return skuInfos.Find((PaymentSkuInfo x) => x.productId == productId);
	}

	public bool isGoogleReward(string productId)
	{
		return productId.EndsWith(".rew");
	}

	private void sendPaymentErrorLog(string method, string message)
	{
		long ticks = DateTime.Now.Ticks;
		if (method == lastErrorMethod && message == lastErrorMessage && ticks - lastLogTimeTicks < 600000000)
		{
			sameLogCount++;
			return;
		}
		LocalLog.AccumulateTraceLog(((sameLogCount > 0) ? $"same log : {sameLogCount}\n" : string.Empty) + "\n method:" + method + " message: " + message);
		lastLogTimeTicks = ticks;
		lastErrorMethod = method;
		lastErrorMessage = message;
		sameLogCount = 0;
	}
}
