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

public class CreateItemList : MonoBehaviour
{
	private static CreateItemList main;

	[SerializeField]
	private GameObject ItemListObj;

	[SerializeField]
	private GameObject BirthInputObj;

	[SerializeField]
	private NguiObjs BuyButtons;

	[SerializeField]
	private UIScrollView CrystalScrollView;

	[SerializeField]
	private UIScrollBar ScrollBar;

	[SerializeField]
	private GameObject ButtonBase;

	[SerializeField]
	private GameObject OneButtonBase;

	[SerializeField]
	private UILabel BtnInfo0Label;

	[SerializeField]
	private UILabel BtnInfo1Label;

	[SerializeField]
	private UILabel OneButtonLabel;

	[SerializeField]
	private TweenAlpha ItemListWindowAlpha;

	[SerializeField]
	private TweenAlpha BirthWindowAlpha;

	[SerializeField]
	private UILabel MyCrystalNumLabel;

	[SerializeField]
	private GameObject BtnFundSettlementObj;

	[SerializeField]
	private GameObject BtnLegalObj;

	[SerializeField]
	private UILabel BirthLabel1;

	[SerializeField]
	private UILabel BirthLabel2;

	[SerializeField]
	private UILabel BirthAgeLabel;

	[SerializeField]
	private UILabel BirthLimitLabel;

	[SerializeField]
	private UILabel BirthPriceLabel;

	[SerializeField]
	private UILabel BirthWarnLabel;

	[SerializeField]
	private UILabel InputExampleLabel;

	[SerializeField]
	private UIInput UIInputObject;

	[SerializeField]
	private GameObject _noInputCollider;

	public static int BirthDayUpdateServerTime;

	public static float BirthDayUpdateRealTime;

	private string productId = "";

	private int ProductIndex;

	private string DateOfBirth = "";

	private NetworkManager networkManager;

	private DateTime NowTime;

	private List<NguiObjs> _itemObjectList;

	private List<string> _notDispItemList = new List<string>();

	[HideInInspector]
	public DialogBase ParentDialogBase;

	private const int BIRTH_DAY_NUMBER_DIGITS = 6;

	private const int CHILD_YEAR = 18;

	private const int CRYSTAL_LIMIT_UNDER = 2500;

	private const int CRYSTAL_LIMIT_TOP = 5000;

	private const int EN_LIMIT_UNDER = 5000;

	private const int EN_LIMIT_TOP = 10000;

	private const int ERROR_WINDOW_DEPTH = 50;

	private const string DEFAULT_BIRTH_DAY = "0";

	private const string FORMAT_CONVERT_DATE_BIRTH = "{0}/{1}/15";

	private const int NGUI_SEPARATOR = 0;

	private const int NGUI_ITEM_SPRITE = 0;

	public string ScrollToProductId;

	private Vector3 _lastScrollPosition;

	private const float SCROLL_OFFSET = 10f;

	private const float SCROLL_DELAY = 0f;

	private const float SCROLL_DELAY_LONG = 0f;

	private const float SCROLL_TIME = 0f;

	public bool IsOnlyInputBirthday { get; set; }

	public Action OnFinishUpdateBirthday { get; set; }

	public static CreateItemList GetInstance()
	{
		return main;
	}

	private void Start()
	{
		main = this;
		if (networkManager == null)
		{
			networkManager = Toolbox.NetworkManager;
		}
		SystemText systemText = Data.SystemText;
		PaymentPC instance = PaymentPC.GetInstance();
		instance.ConsumePurchaseSucceeded += PaymentSuccessed;
		BirthLabel1.text = systemText.Get("Shop_0029");
		BirthLabel2.text = systemText.Get("Shop_0030");
		BirthAgeLabel.text = systemText.Get("Shop_0035") + "\n" + systemText.Get("Shop_0036") + "\n" + systemText.Get("Shop_0037");
		BirthLimitLabel.text = systemText.Get("Shop_0038") + "\n" + systemText.Get("Shop_0038") + "\n" + systemText.Get("Shop_0040");
		string text;
		string text2;
		if (Data.SystemText.RegionCode == Global.LANG_TYPE.Ger.ToString())
		{
			CultureInfo cultureInfo = new CultureInfo("de-de");
			text = 2500.ToString("N0", cultureInfo);
			text2 = 5000.ToString("N0", cultureInfo);
		}
		else
		{
			text = $"{2500:N0}";
			text2 = $"{5000:N0}";
		}
		BirthPriceLabel.text = systemText.Get("Shop_0039", text) + "\n" + systemText.Get("Shop_0039", text2);
		BirthWarnLabel.text = systemText.Get("Shop_0031");
		InputExampleLabel.text = systemText.Get("Shop_0068");
		InputExampleLabel.gameObject.SetActive(value: true);
		ParentDialogBase.SetButtonDisable(isEnableOK: true);
		Dictionary<string, string> productPurchaseLimitList = instance.ProductPurchaseLimitList;
		Dictionary<string, string> productPurchaseNumberList = instance.ProductPurchaseNumberList;
		Dictionary<string, string> productCsvIdList = instance.ProductCsvIdList;
		_notDispItemList.Clear();
		if (productPurchaseNumberList.Count != 0)
		{
			foreach (KeyValuePair<string, string> item in productCsvIdList)
			{
				if (productPurchaseNumberList.ContainsKey(item.Value) && int.Parse(productPurchaseLimitList[item.Value]) <= int.Parse(productPurchaseNumberList[item.Value]))
				{
					_notDispItemList.Add(item.Value);
				}
			}
		}
		InitScrollView(_notDispItemList);
		UpdateCrystalCount();
		if (IsBirthdayNotInput())
		{
			BirthInputObj.SetActive(value: true);
			BirthWindowAlpha.PlayForward();
			return;
		}
		ItemListObj.SetActive(value: true);
		ItemListWindowAlpha.PlayForward();
		ParentDialogBase.SetButtonLayout(DialogBase.ButtonLayout.CloseBtn);
		ParentDialogBase.SetButtonDisable(isEnableOK: false);
		ParentDialogBase.onPushButton1 = delegate
		{
			ParentDialogBase.Close();
		};
		UIManager.GetInstance().closeInSceneCenterLoading();
		CrystalScrollView.ResetPosition();
		ScrollBar.value = 0f;
	}

	public static bool IsBirthdayNotInput()
	{
		return PlayerStaticData.UserBirthDay == "0";
	}

	private void Update()
	{
		CheckScrollToItem(0f);
		if (PlayerStaticData.UserBirthDay.Length != 6)
		{
			if (UIInputObject.isSelected)
			{
				InputExampleLabel.gameObject.SetActive(value: false);
			}
			else if (UIInputObject.value.Length == 0)
			{
				InputExampleLabel.gameObject.SetActive(value: true);
			}
		}
	}

	protected void InitScrollView(List<string> inDeleteIdList = null)
	{
		PaymentPC instance = PaymentPC.GetInstance();
		List<string> productIdList = instance.ProductIdList;
		Dictionary<string, string> productCsvIdList = instance.ProductCsvIdList;
		Dictionary<string, string> productNameList = instance.ProductNameList;
		Dictionary<string, string> formatProductPriceList = instance.FormatProductPriceList;
		Dictionary<string, string> productImageNameList = instance.ProductImageNameList;
		Dictionary<string, bool> productIsSpecialShop = instance.ProductIsSpecialShop;
		SystemText systemText = Data.SystemText;
		float num = 0f;
		float num2 = 0f;
		int num3 = 0;
		_itemObjectList = new List<NguiObjs>(productIdList.Count);
		for (int i = 0; i < productIdList.Count; i++)
		{
			string key = productIdList[i];
			if ((inDeleteIdList == null || !inDeleteIdList.Contains(productCsvIdList[key])) && !productIsSpecialShop[key] && productNameList.ContainsKey(key) && formatProductPriceList.ContainsKey(key))
			{
				NguiObjs component = NGUITools.AddChild(CrystalScrollView.gameObject, BuyButtons.gameObject).GetComponent<NguiObjs>();
				_itemObjectList.Add(component);
				component.gameObject.SetActive(value: true);
				component.labels[0].text = productNameList[key];
				component.labels[1].text = systemText.Get("Shop_0083") + "$" + formatProductPriceList[key];
				component.labels[2].text = systemText.Get("Shop_0041");
				component.buttons[0].gameObject.name = i.ToString();
				UIEventListener uIEventListener = UIEventListener.Get(component.buttons[0].gameObject);
				uIEventListener.onClick = (UIEventListener.VoidDelegate)Delegate.Combine(uIEventListener.onClick, new UIEventListener.VoidDelegate(BuyCrystalButtonClickCallBack));
				num2 = component.GetComponent<UISprite>().height;
				num = (float)num3 * num2;
				component.transform.localPosition = new Vector3(0f, 0f - num, 0f);
				component.sprites[0].spriteName = productImageNameList[key];
				if (i == productIdList.Count - 1)
				{
					component.objs[0].SetActive(value: false);
				}
				else
				{
					component.objs[0].SetActive(value: true);
				}
				num3++;
			}
		}
		OneButtonBase.SetActive(value: false);
		ButtonBase.SetActive(value: false);
		if (CustomPreference.GetTextLanguage() == Global.LANG_TYPE.Kor.ToString())
		{
			OneButtonBase.SetActive(value: true);
			OneButtonBase.transform.localPosition = new Vector3(0f, 0f - (num + num2 / 2f), 0f);
			OneButtonLabel.text = systemText.Get("Shop_0125");
		}
		CrystalScrollView.ResetPosition();
		ScrollBar.value = 0f;
	}

	private void _PaymentListErrorDialog()
	{
		if (BattleManagerBase.GetIns() == null)
		{
			DialogBase dialogBase = UIManager.GetInstance().CreateDialogClose();
			dialogBase.SetTitleLabel(Data.SystemText.Get("Shop_0094"));
			dialogBase.SetText(Data.SystemText.Get("Shop_0093"));
			dialogBase.SetButtonLayout(DialogBase.ButtonLayout.OkBtn);
			dialogBase.SetPanelDepth(100);
		}
	}

	public void BirthUpdateButtonClickCallBack()
	{
		DateOfBirth = UIInputObject.value;
		DialogBase dialogBase = UIManager.GetInstance().CreateDialogClose();
		dialogBase.SetReturnMsg(base.gameObject, "BirthUpdateTask");
		dialogBase.SetTitleLabel(Data.SystemText.Get("Shop_0070"));
		if (DateTime.TryParse($"{DateOfBirth.Substring(0, 4)}/{DateOfBirth.Substring(4, 2)}/15", out var result))
		{
			result = TimeZoneInfo.ConvertTimeToUtc(result);
			string text = ConvertTime.ToLocal(result, ConvertTime.FORMAT.YEAR_MONTH);
			dialogBase.SetText(Data.SystemText.Get("Shop_0071", text));
		}
		else
		{
			dialogBase.SetText(Data.SystemText.Get("Shop_0071", DateOfBirth));
		}
		dialogBase.SetButtonLayout(DialogBase.ButtonLayout.BlueBtn_CancelBtn);
		dialogBase.SetButtonText(Data.SystemText.Get("Dia_BuyCrystal_002_Button"));
		dialogBase.SetPanelDepth(100);
	}

	private void BirthUpdateTask()
	{
		UpdateBirthTask updateBirthTask = new UpdateBirthTask();
		updateBirthTask.SetParameter(DateOfBirth);
		StartCoroutine(networkManager.Connect(updateBirthTask, OnUpdateBirthFinished));
	}

	private void OnUpdateBirthFinished(NetworkTask.ResultCode code)
	{
		PlayerStaticData.UserBirthDay = UIInputObject.value;
		DialogBase dialogBase = UIManager.GetInstance().CreateDialogClose();
		dialogBase.SetTitleLabel(Data.SystemText.Get("Dia_BuyCrystal_003_Title"));
		dialogBase.SetText(Data.SystemText.Get("Shop_0069"));
		dialogBase.SetButtonLayout(DialogBase.ButtonLayout.OkBtn);
		dialogBase.SetPanelDepth(100);
		if (!IsOnlyInputBirthday)
		{
			dialogBase.OnClose = BirthCloseAndItemOpen;
			return;
		}
		dialogBase.OnClose = delegate
		{
			OnFinishUpdateBirthday.Call();
		};
	}

	protected void BirthCloseAndItemOpen()
	{
		BirthWindowAlpha.PlayReverse();
		if (IsChildCheckDialog())
		{
			ChildWarningDialog();
		}
		else
		{
			ActivateItemList();
		}
	}

	private void ActivateItemList()
	{
		ItemListObj.SetActive(value: true);
		ParentDialogBase.SetButtonLayout(DialogBase.ButtonLayout.CloseBtn);
		ParentDialogBase.SetButtonDisable(isEnableOK: false);
		ParentDialogBase.onPushButton1 = delegate
		{
			ParentDialogBase.Close();
		};
		ItemListWindowAlpha.PlayForward();
		CheckScrollToItem(0f);
	}

	public void BirthCancelButtonClickCallBack()
	{
		ParentDialogBase.CloseWithoutSelect();
	}

	public void BirthInputOnChange()
	{
		if (UIInputObject.value.Length == 6)
		{
			ParentDialogBase.SetButtonDisable(isEnableOK: false);
		}
		else
		{
			ParentDialogBase.SetButtonDisable(isEnableOK: true);
		}
	}

	private void ChildWarningDialog()
	{
		DialogBase dialogBase = UIManager.GetInstance().CreateDialogClose();
		dialogBase.SetTitleLabel(Data.SystemText.Get("Shop_0078"));
		dialogBase.SetText(Data.SystemText.Get("Shop_0079"));
		dialogBase.SetButtonLayout(DialogBase.ButtonLayout.OkBtn);
		dialogBase.SetPanelDepth(100);
		dialogBase.OnClose = ActivateItemList;
	}

	private void BuyCrystalButtonClickCallBack(GameObject g)
	{
		GameMgr.GetIns().GetSoundMgr().PlaySe(Se.TYPE.SYS_BTN_DECIDE);
		ProductIndex = int.Parse(g.name);
		StartPaymentDialog();
	}

	private void StartPaymentDialog()
	{
		productId = PaymentPC.GetInstance().ProductIdList[ProductIndex];
		Dictionary<string, string> productNameList = PaymentPC.GetInstance().ProductNameList;
		if (PlayerStaticData.IsPurchaseNotificationOfLootBox())
		{
			LootBoxDialogUtility.CreatePurchaseNotificationLootBoxDialog(Data.SystemText.Get("Dia_BuyCrystal_004_Title"), productNameList[productId], StartPayment, CancelPayment);
			return;
		}
		DialogBase dialogBase = UIManager.GetInstance().CreateDialogClose();
		dialogBase.SetTitleLabel(Data.SystemText.Get("Dia_BuyCrystal_004_Title"));
		dialogBase.SetText(Data.SystemText.Get("Shop_0017", productNameList[productId]));
		dialogBase.SetButtonLayout(DialogBase.ButtonLayout.BlueBtn_CancelBtn);
		dialogBase.SetButtonText(Data.SystemText.Get("Dia_BuyCrystal_004_Button"));
		dialogBase.SetReturnMsg(base.gameObject, "StartPayment", "CancelPayment");
		dialogBase.SetPanelDepth(100);
	}

	private void CancelPayment()
	{
		UIManager.GetInstance().WebViewHelper.DestroyWebView();
	}

	private void StartPayment()
	{
		PaymentPC.GetInstance().purchaceStart(productId);
	}

	private void PaymentSuccessed()
	{
		try
		{
			Dictionary<string, string> productPurchaseLimitList = PaymentPC.GetInstance().ProductPurchaseLimitList;
			string lastPaymentId = Data.Load.data._userCrystalCount._lastPaymentId;
			int lastPaymentItemBuyNumber = Data.Load.data._userCrystalCount._lastPaymentItemBuyNumber;
			if (lastPaymentId != null && int.Parse(productPurchaseLimitList[lastPaymentId]) <= lastPaymentItemBuyNumber)
			{
				if (!_notDispItemList.Contains(lastPaymentId))
				{
					_notDispItemList.Add(lastPaymentId);
				}
				for (int i = 0; i < _itemObjectList.Count; i++)
				{
					UnityEngine.Object.Destroy(_itemObjectList[i].gameObject);
				}
				_itemObjectList.Clear();
				InitScrollView(_notDispItemList);
			}
		}
		catch (Exception ex)
		{
			LocalLog.AccumulateTraceLog("Payment suceeded but exception is captured :" + ex);
		}
	}

	public void UpdateCrystalCount()
	{
		MyCrystalNumLabel.text = PlayerStaticData.UserCrystalCount.ToString();
	}

	public void FundSettlementButtonClickCallBack()
	{
		GameMgr.GetIns().GetSoundMgr().PlaySe(Se.TYPE.SYS_BTN_DECIDE);
		UIManager.GetInstance().WebViewHelper.OpenWebView(WebViewHelper.WebViewType.FUND_SETTLEMENT);
	}

	public void LegalButtonClickCallBack()
	{
		GameMgr.GetIns().GetSoundMgr().PlaySe(Se.TYPE.SYS_BTN_DECIDE);
		UIManager.GetInstance().WebViewHelper.OpenWebView(WebViewHelper.WebViewType.LEGALTEXT);
	}

	public void OneButtonClickCallBack()
	{
		GameMgr.GetIns().GetSoundMgr().PlaySe(Se.TYPE.SYS_BTN_DECIDE);
		if (CustomPreference.GetTextLanguage() == Global.LANG_TYPE.Kor.ToString())
		{
			UIManager.GetInstance().WebViewHelper.OpenWebView(WebViewHelper.WebViewType.KOREA_CRYSTAL_PAGE);
		}
	}

	public bool IsChildCheckDialog()
	{
		if (BirthDayUpdateServerTime != 0)
		{
			int year = int.Parse(PlayerStaticData.UserBirthDay.Substring(0, 4));
			int month = int.Parse(PlayerStaticData.UserBirthDay.Substring(4, 2));
			DateTime dateTime = new DateTime(year, month, 1);
			DateTime dateTime2 = UnixTimeToDateTime(BirthDayUpdateServerTime + (int)(Time.realtimeSinceStartup - BirthDayUpdateRealTime));
			DateTime dateTime3 = new DateTime(1, 1, 1);
			TimeSpan timeSpan = dateTime2 - dateTime;
			int num = (dateTime3 + timeSpan).Year - 1;
			int num2 = (dateTime3 + timeSpan).Month - 1;
			if (num < 18 || (num == 18 && num2 == 0))
			{
				return true;
			}
			return false;
		}
		return false;
	}

	protected DateTime UnixTimeToDateTime(int unixTime)
	{
		return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(unixTime);
	}

	private void StartScrollToIndex(int index, float delay)
	{
		Vector3 localPosition = CrystalScrollView.transform.localPosition;
		Vector3 vector = localPosition - _itemObjectList[index].transform.localPosition;
		vector.y += 10f;
		_lastScrollPosition = localPosition;
		_noInputCollider.SetActive(value: true);
		iTween.ValueTo(base.gameObject, iTween.Hash("from", localPosition, "to", vector, "delay", delay, "time", 0f, "easetype", iTween.EaseType.easeInOutQuad, "onupdate", "ScrollViewUpdate", "oncomplete", "DeactivateCollider"));
	}

	private void ScrollViewUpdate(Vector3 v)
	{
		CrystalScrollView.MoveRelative(v - _lastScrollPosition);
		CrystalScrollView.RestrictWithinBounds(instant: true);
		_lastScrollPosition = v;
	}

	private void DeactivateCollider()
	{
		_noInputCollider.SetActive(value: false);
	}

	private int GetIndexFromProductId(string id)
	{
		List<string> idList = PaymentPC.GetInstance().IdList;
		if (_notDispItemList != null)
		{
			for (int i = 0; i < _notDispItemList.Count; i++)
			{
				idList.Remove(_notDispItemList[i]);
			}
		}
		return idList.FindIndex((string x) => x == id);
	}

	private void CheckScrollToItem(float delay)
	{
		if (CrystalScrollView.isActiveAndEnabled && !string.IsNullOrEmpty(ScrollToProductId))
		{
			int indexFromProductId = GetIndexFromProductId(ScrollToProductId);
			if (indexFromProductId > 0)
			{
				StartScrollToIndex(indexFromProductId, delay);
			}
			ScrollToProductId = null;
		}
	}
}
