using System;
using System.Collections;
using Cute;
using UnityEngine;
using Wizard;
using Wizard.Battle.Recovery;
using Wizard.Title;

public class TitleUI : UIBase
{
	public enum ImageType
	{
		Default,
		Special1,
		Special2,
		Special3
	}

	public enum BgmType
	{
		Default,
		Special1,
		Special2
	}

	private class GuidelineParam
	{
		public float DisplayTime { get; private set; }

		public bool IncludeFadeInOut { get; private set; }

		public bool EnableTouch { get; private set; }

		public float FadeInTime { get; private set; }

		public float PanelFadeOutTime { get; private set; }

		public float BgFadeOutTime { get; private set; }

		public GuidelineParam(float displayTime, bool includeFadeInOut, bool enableTouch, float fadeInTime, float panelFadeOutTime, float bgFadeOutTime)
		{
			DisplayTime = displayTime;
			IncludeFadeInOut = includeFadeInOut;
			EnableTouch = enableTouch;
			FadeInTime = fadeInTime;
			PanelFadeOutTime = panelFadeOutTime;
			BgFadeOutTime = bgFadeOutTime;
		}
	}

	public const string DEFAULT_TITLE_ID = "0";

	public const string USE_LOCAL_PREFAB_ID = "1";

	private const string DEFAULT_TITLE_PATH = "Title/NormalTitle/NormalTitle";

	[SerializeField]
	private GameObject BtnTouchStart;

	[SerializeField]
	private UILabel VersionIDLabel;

	[SerializeField]
	private UILabel UserIDLabel;

	[SerializeField]
	private GameObject _userIdRoot;

	[SerializeField]
	private UIButton ButtonMenu;

	[SerializeField]
	private UILabel ButtonMenuLabel;

	[SerializeField]
	private GameObject ButtonMenuObject;

	[SerializeField]
	private UIButton ButtonTransfer;

	[SerializeField]
	private UILabel ButtonTransferLabel;

	[SerializeField]
	private NguiObjs LoginInput;

	[SerializeField]
	private GameObject _korGuidelineRoot;

	[SerializeField]
	private UIPanel _korGuidelineDisplayRootPanel;

	[SerializeField]
	private UISprite _korGuidelineBG;

	[SerializeField]
	private GameObject _jpnGuidelineRoot;

	[SerializeField]
	private UIPanel _jpnGuidelineDisplayRootPanel;

	[SerializeField]
	private UISprite _jpnGuidelineBG;

	[SerializeField]
	private float _jpnGuidelineDisplayTime;

	[SerializeField]
	private bool _jpnGuidelineIncludeFadeInOut;

	[SerializeField]
	private GameObject _parentTitleView;

	[SerializeField]
	private SpecialTitleAssetBundle _specialTitle;

	private GameObject _normalTitle;

	private DialogBase dia;

	private GameSetup _gameSetup;

	private bool _isAutoCacheExecution;

	private Coroutine _fadeInCoroutine;

	private bool _isSteamKor;

	private DataMgr _dataManager;

	private SoundMgr _soundManager;

	private bool IsDownloadTitle
	{
		get
		{
			if (_dataManager.TitleId != "0")
			{
				return _dataManager.TitleId != "1";
			}
			return false;
		}
	}

	public override void onFirstStart()
	{
		if (CustomPreference.GetTextLanguage() == Global.LANG_TYPE.Kor.ToString())
		{
			_isSteamKor = true;
		}
		else
		{
			_isSteamKor = false;
		}
		string appVersionName = Toolbox.DeviceManager.GetAppVersionName();
		try
		{
			VideoHostingUtil.AutoPausePublishing(isSave: true);
			VideoHostingUtil.AutoStopRecording(isSave: true);
		}
		catch (Exception)
		{
			LocalLog.AccumulateTraceLog("690753 VideoHostingUtil InitializeException");
			throw;
		}
		Toolbox.SceneManager.SceneChangeParameter.KeepAssets = false;
		VersionIDLabel.text = "Ver." + appVersionName;
		if (Certification.ViewerId > 0)
		{
			SetUserIdLabel(Certification.ViewerId);
		}
		else
		{
			try
			{
				RecoveryRecordManagerBase.DeleteRecoveryFile();
				SetUserIdLabel(Certification.ViewerId);
			}
			catch (Exception)
			{
				LocalLog.AccumulateTraceLog("690753 DeleteRecoveryDataException");
				throw;
			}
		}
		SystemText systemText = Data.SystemText;
		try
		{
			ButtonMenuLabel.text = systemText.Get("Title_0006");
			ButtonTransferLabel.text = systemText.Get("Account_0001");
		}
		catch (Exception)
		{
			LocalLog.AccumulateTraceLog("690753 ButtonTextSetException");
			throw;
		}
		try
		{
			base.onFirstStart();
		}
		catch (Exception)
		{
			LocalLog.AccumulateTraceLog("690753 BaseFirstStartException");
		}
		GameMgr ins = GameMgr.GetIns();
		_dataManager = ins.GetDataMgr();
		_soundManager = ins.GetSoundMgr();
		try
		{
			SetChangeableTitleUI();
		}
		catch (Exception)
		{
			LocalLog.AccumulateTraceLog("690753 SetChangeableTitleUIException");
		}
		try
		{
			ins.GetGameObjMgr().GetUIContainer().SetActive(value: false);
			Toolbox.AssetManager.AddNoUnloadAssetGroupName("card_foil");
			_gameSetup = new GameSetup(this);
		}
		catch (Exception)
		{
			LocalLog.AccumulateTraceLog("690753 InitializeExeption");
		}
		try
		{
			UIEventListener.Get(BtnTouchStart.gameObject).onClick = OnClickStartButton;
			UIEventListener.Get(ButtonMenu.gameObject).onClick = OnClickMenuButton;
			UIEventListener.Get(ButtonTransfer.gameObject).onClick = OnClickTransferButton;
		}
		catch (Exception)
		{
			LocalLog.AccumulateTraceLog("690753 ButtonCallBackException");
		}
		if (!DisplayGuideline())
		{
			PlayChangeableTitleBGM();
		}
		UIManager.GetInstance().CreatFadeOpen();
		if (PlayerPrefsWrapper.GetBool(PlayerPrefsWrapper.AUTO_CACHE_CLEAR_FLAG))
		{
			PlayerPrefsWrapper.SetBool(PlayerPrefsWrapper.AUTO_CACHE_CLEAR_FLAG, flag: false);
			_isAutoCacheExecution = true;
			ClearCache();
		}
	}

	private void SetUserIdLabel(int id)
	{
		if (id > 0)
		{
			UserIDLabel.text = VideoHostingUtil.GetUserIDHidden($"ID: {id:#,0}".Replace(",", " "));
		}
		else
		{
			UserIDLabel.text = "";
		}
		_userIdRoot.SetActive(id > 0);
	}

	private void PlayChangeableTitleBGM()
	{
		switch (_dataManager.TitleId)
		{
		case "0":
			_soundManager.PlayBGM(Bgm.BGM_TYPE.TITLE);
			break;
		case "1":
			_soundManager.PlayBGM(Bgm.BGM_TYPE.TITLE_SPECIAL_1);
			break;
		default:
			_specialTitle.PlayBGM();
			break;
		}
	}

	private void SetChangeableTitleUI()
	{
		switch (_dataManager.TitleId)
		{
		case "0":
			_normalTitle = InitializeLocalPrefabTitle("Title/NormalTitle/NormalTitle");
			break;
		case "1":
			InitializeLocalPrefabTitle("Title/SpecialTitle1/SpecialTitle1");
			break;
		default:
			_specialTitle.Initialize(_dataManager.TitleId);
			break;
		}
	}

	private GameObject InitializeLocalPrefabTitle(string path)
	{
		ChangeableTitleUIParts component = NGUITools.AddChild(_parentTitleView, Resources.Load(path) as GameObject).GetComponent<ChangeableTitleUIParts>();
		if (component != null)
		{
			component.Init();
			return component.gameObject;
		}
		return null;
	}

	private bool DisplayGuideline()
	{
		bool result = false;
		try
		{
			if (CustomPreference.GetTextLanguage() == Global.LANG_TYPE.Jpn.ToString())
			{
				GuidelineParam param = new GuidelineParam(_jpnGuidelineDisplayTime, _jpnGuidelineIncludeFadeInOut, enableTouch: true, 0.5f, 0.5f, 0.5f);
				_fadeInCoroutine = StartCoroutine(GuidelineFadeCoroutine(_jpnGuidelineRoot, _jpnGuidelineDisplayRootPanel, _jpnGuidelineBG, param));
				result = true;
			}
			else
			{
				_jpnGuidelineRoot.SetActive(value: false);
			}
		}
		catch (Exception)
		{
			LocalLog.AccumulateTraceLog("690753 DisplayGuideline.JapanInitializeException");
			throw;
		}
		try
		{
			if (_isSteamKor)
			{
				GuidelineParam param2 = new GuidelineParam(3f, includeFadeInOut: false, enableTouch: false, 0.3f, 0.3f, 0.3f);
				_fadeInCoroutine = StartCoroutine(GuidelineFadeCoroutine(_korGuidelineRoot, _korGuidelineDisplayRootPanel, _korGuidelineBG, param2));
				result = true;
			}
			else
			{
				_korGuidelineRoot.SetActive(value: false);
			}
		}
		catch (Exception)
		{
			LocalLog.AccumulateTraceLog("690753 DisplayGuideline.KorInitializeException");
			throw;
		}
		return result;
	}

	private IEnumerator GuidelineFadeCoroutine(GameObject guidelineRoot, UIPanel guidelineRootPanel, UISprite bg, GuidelineParam param)
	{
		guidelineRoot.SetActive(value: true);
		guidelineRootPanel.alpha = 0f;
		TweenAlpha.Begin(guidelineRootPanel.gameObject, param.FadeInTime, 1f);
		if (param.EnableTouch)
		{
			UIEventListener uIEventListener = UIEventListener.Get(bg.gameObject);
			uIEventListener.onClick = (UIEventListener.VoidDelegate)Delegate.Combine(uIEventListener.onClick, (UIEventListener.VoidDelegate)delegate(GameObject g)
			{
				SkipGuidelineEvent(g, guidelineRoot, guidelineRootPanel, bg, param, _fadeInCoroutine);
			});
		}
		yield return new WaitForSeconds(param.FadeInTime);
		float time = 0f;
		float waitFadeTime = param.DisplayTime;
		if (param.IncludeFadeInOut)
		{
			waitFadeTime = waitFadeTime - param.FadeInTime - param.PanelFadeOutTime - param.BgFadeOutTime;
		}
		while (true)
		{
			time += Time.deltaTime;
			if (time > waitFadeTime)
			{
				break;
			}
			yield return null;
		}
		StartCoroutine(EndGuideline(guidelineRoot, guidelineRootPanel, bg, param));
	}

	private void SkipGuidelineEvent(GameObject g, GameObject guidelineRoot, UIPanel guidelineRootPanel, UISprite bg, GuidelineParam param, Coroutine fadeInCoroutine)
	{
		StopCoroutine(fadeInCoroutine);
		StartCoroutine(EndGuideline(guidelineRoot, guidelineRootPanel, bg, param));
	}

	private IEnumerator EndGuideline(GameObject guidelineRoot, UIPanel guidelineRootPanel, UISprite bg, GuidelineParam param)
	{
		if (param.EnableTouch)
		{
			UIEventListener.Get(bg.gameObject).onClick = null;
		}
		TweenAlpha.Begin(guidelineRootPanel.gameObject, param.PanelFadeOutTime, 0f);
		yield return new WaitForSeconds(param.PanelFadeOutTime);
		PlayChangeableTitleBGM();
		TweenAlpha.Begin(bg.gameObject, param.BgFadeOutTime, 0f);
		yield return new WaitForSeconds(param.BgFadeOutTime);
		guidelineRoot.SetActive(value: false);
	}

	public bool IsEnableClickButton()
	{
		if (!_gameSetup.IsRunning)
		{
			return !_isAutoCacheExecution;
		}
		return false;
	}

	private void OnClickStartButton(GameObject g)
	{
		if (IsEnableClickButton())
		{
			NtDataTranslateManager.GetInstance().ShowCygamesStatement(attendSetLanguage, fromTitle: true);
		}
	}

	private void StartCuteCertification()
	{
		StartCoroutine(cuteCertification(delegate
		{
			if (!ShowRefundDialogIfNeeded())
			{
				attendSocialAccountDataTrans();
			}
		}));
	}

	private void OnClickMenuButton(GameObject g)
	{
		if (IsEnableClickButton())
		{
			_soundManager.PlaySe(Se.TYPE.SYS_COMMON_BUTTON);
			ShowMenu();
		}
	}

	private void OnClickTransferButton(GameObject g)
	{
		if (IsEnableClickButton())
		{
			_soundManager.PlaySe(Se.TYPE.SYS_COMMON_BUTTON);
			StartCoroutine(cuteCertification(ShowTransferMenu));
		}
	}

	private IEnumerator cuteCertification(Action callback)
	{
		UIManager.GetInstance().createInSceneCenterLoading(notBlack: true, notCollider: false, force: false);
		yield return StartCoroutine(Toolbox.NetworkManager._certification.Login());
		while (!Toolbox.BootNetwork.IsDoneGameStartCheck)
		{
			yield return 0;
		}
		UIManager.GetInstance().closeInSceneCenterLoading();
		CustomPreference.createResourcePath();
		callback?.Invoke();
	}

	private void attendSetLanguage()
	{
		Action onFinish = delegate
		{
			StartCuteCertification();
		};
		if (string.IsNullOrEmpty(Toolbox.SavedataManager.GetString("LANG_FIRST_SET")))
		{
			SwitchLanguage.Create(isForceConfirmDialog: true, isTitle: true, delegate
			{
				onFinish();
			}, attendSocialAccountDataTrans);
		}
		else
		{
			onFinish();
		}
	}

	private bool ShowRefundDialogIfNeeded()
	{
		string refundUrl = GameStartCheckTask.RefundUrl;
		if (string.IsNullOrEmpty(refundUrl))
		{
			return false;
		}
		OutOfService.ShowRefundDialog(refundUrl);
		return true;
	}

	private void attendSocialAccountDataTrans()
	{
		if (GameStartCheckTask.IsSocialAccountDataTransNotSetAndTutorialClear && !GameStartCheckTask.HasAppliedForAccountDeletion && PlayerStaticData._tosAgreementState != PlayerStaticData.AgreementState.Reset && PlayerStaticData._privacyPolicyAgreementState != PlayerStaticData.AgreementState.Reset && PlayerStaticData.KorAuthorityAgreementState != PlayerStaticData.AgreementState.Reset && !UIManager.GetInstance().IsAutoCacheClearAfter)
		{
			ShowAccountConnectWindow();
		}
		else
		{
			startGameSetup();
		}
	}

	private void startGameSetup()
	{
		LocalLog.RecordFreezeLogIfLoadErrorOccured();
		SetUserIdLabel(Certification.ViewerId);
		if (!_gameSetup.IsRunning)
		{
			StartUpDateRegion();
		}
	}

	private void StartUpDateRegion()
	{
		new UserRegionUpdater().UpDateRegion(delegate
		{
			StartCoroutine(_gameSetup.StartSetup());
		});
	}

	private void ShowMenu()
	{
		GameObject gameObject = UnityEngine.Object.Instantiate(ButtonMenuObject);
		TitleMenu component = gameObject.GetComponent<TitleMenu>();
		SystemText systemText = Data.SystemText;
		dia = UIManager.GetInstance().CreateDialogClose();
		dia.SetTitleLabel(systemText.Get("Title_0006"));
		dia.SetButtonLayout(DialogBase.ButtonLayout.CloseBtn);
		dia.SetObj(gameObject);
		dia.SetPanelDepth(1);
		component.ParentObject = base.gameObject;
	}

	private void ShowTransferMenu()
	{
		SetUserIdLabel(Certification.ViewerId);
		SystemText systemText = Data.SystemText;
		dia = UIManager.GetInstance().CreateDialogClose();
		dia.SetSize(DialogBase.Size.M);
		dia.SetTitleLabel(systemText.Get("Account_0001"));
		string text = systemText.Get("OtherTop_0020");
		dia.SetText(text);
		dia.SetButtonLayout(DialogBase.ButtonLayout.BlueBtn_CancelBtn);
		dia.SetButtonText(systemText.Get("Account_0089"));
		EventDelegate method_btn = new EventDelegate(delegate
		{
			UIManager.GetInstance().AccountTransferHelper.CreateAccountTransferDialog(AccountBase.DisplayType.TITLE, AccountBase.TransitionOriginalScreen.TITLE);
		});
		dia.SetButtonDelegate(method_btn);
	}

	public void ClearCache()
	{
		if (dia != null)
		{
			dia.CloseWithoutSelect();
		}
		if (IsViewerIdDecided())
		{
			ClientCacheClearTask task = new ClientCacheClearTask();
			StartCoroutine(Toolbox.NetworkManager.Connect(task, delegate
			{
				ClearCacheCore();
			}));
		}
		else
		{
			ClearCacheCore();
		}
	}

	private void ClearCacheCore()
	{
		UIManager.GetInstance().createInSceneLoading();
		if (IsDownloadTitle)
		{
			_soundManager.PlayBGM(Bgm.BGM_TYPE.TITLE);
		}
		StartCoroutine(WaitCoroutine(0.2f, delegate
		{
			if (IsDownloadTitle)
			{
				_specialTitle.UnloadBGM();
				_specialTitle.RemoveSpecialTitle();
			}
			WebViewManager.getInstance().CacheClear();
			StartCoroutine(StartCleanCache());
			CardMasterLocalFileUtility.DeleteAllCardMasterLocalFile();
			RecoveryRecordManagerBase.DeleteRecoveryFile();
			LocalLog.ClearAllLog();
			NativePluginWrapper.ClearWWWCache();
			LocalLog.ClearTraceLog();
			TaskManager.GetInstance().ClearLastLogKey();
			NewReplayBattleMgr.DeleteReplayFiles();
			if (_normalTitle == null && IsDownloadTitle)
			{
				_normalTitle = InitializeLocalPrefabTitle("Title/NormalTitle/NormalTitle");
			}
			LocalLog.AccumulateTraceLog("Clear Cache");
		}));
	}

	private IEnumerator WaitCoroutine(float time, Action onFinish)
	{
		yield return new WaitForSeconds(time);
		onFinish.Call();
	}

	public void DeleteUserData()
	{
		if (dia != null)
		{
			dia.CloseWithoutSelect();
		}
		if (IsViewerIdDecided())
		{
			DeleteUserDataTask task = new DeleteUserDataTask();
			StartCoroutine(Toolbox.NetworkManager.Connect(task, delegate
			{
				DeleteUserDataCore();
				CreateDeleteUserDataDialog();
			}));
		}
		else
		{
			DeleteUserDataCore();
			CreateDeleteUserDataDialog();
		}
	}

	private void DeleteUserDataCore()
	{
		Certification.InitializeFileds();
		Toolbox.SavedataManager.DeleteAll();
		LocalLog.ClearAllLog();
		RecoveryRecordManagerBase.DeleteRecoveryFile();
		GameObject gameObject = GameObject.Find("OmotePlugin");
		if (gameObject != null)
		{
			OmotePlugin component = gameObject.GetComponent<OmotePlugin>();
			if (component != null)
			{
				component.Unregister(isLocalOnly: false);
				OmotePlugin.LocalNotification.CancelAll();
			}
		}
	}

	private void CreateDeleteUserDataDialog()
	{
		DialogBase dialogBase = UIManager.GetInstance().CreateDialogClose();
		dialogBase.SetSize(DialogBase.Size.S);
		dialogBase.SetTitleLabel(Data.SystemText.Get("Common_0021"));
		dialogBase.SetText(Data.SystemText.Get("Title_0050"));
		dialogBase.SetButtonLayout(DialogBase.ButtonLayout.BlueButton);
		dialogBase.SetButtonText(Data.SystemText.Get("Common_0004"));
		dialogBase.OnClose = delegate
		{
			SoftwareReset.exec(null, isFromUserDelete: true);
		};
	}

	private bool IsViewerIdDecided()
	{
		return Certification.ViewerId != 0;
	}

	private IEnumerator StartCleanCache()
	{
		yield return new WaitForSeconds(1f);
		FontChanger.FontReset();
		UILabel[] array = UnityEngine.Object.FindObjectsOfType(typeof(UILabel)) as UILabel[];
		if (array.Length != 0)
		{
			UILabel[] array2 = array;
			foreach (UILabel uILabel in array2)
			{
				if (uILabel != null)
				{
					uILabel.RefreshCustom();
				}
			}
		}
		Toolbox.AssetManager.ClearAllAssetFile();
		Toolbox.AssetManager.ClearAssetCacheAssetBundle();
		while (!Caching.ready)
		{
			yield return null;
		}
		_gameSetup = new GameSetup(this);
		if (!_isAutoCacheExecution)
		{
			SystemText systemText = Data.SystemText;
			dia = UIManager.GetInstance().CreateDialogClose();
			dia.SetTitleLabel(systemText.Get("Title_0007"));
			dia.SetText(systemText.Get("Title_0009"));
			dia.SetButtonLayout(DialogBase.ButtonLayout.OkBtn);
			dia.SetPanelDepth(3000);
		}
		else
		{
			_isAutoCacheExecution = false;
			UIManager.GetInstance().IsAutoCacheClearAfter = true;
			OnClickStartButton(null);
		}
		UIManager.GetInstance().closeInSceneLoading();
	}

	private void ShowAccountConnectWindow()
	{
		SystemText systemText = Data.SystemText;
		dia = UIManager.GetInstance().CreateDialogClose();
		dia.SetSize(DialogBase.Size.M);
		dia.SetTitleLabel(systemText.Get("Account_0082"));
		string text = systemText.Get("Account_0083");
		dia.SetText(text);
		dia.SetButtonLayout(DialogBase.ButtonLayout.BlueBtn_GrayBtn);
		dia.SetButtonText(systemText.Get("Account_0084"), systemText.Get("Account_0085"));
		EventDelegate method_btn = new EventDelegate(delegate
		{
			UIManager.GetInstance().AccountTransferHelper.CreateAccountTransferDialog(AccountBase.DisplayType.ACCOUNT_LINK, AccountBase.TransitionOriginalScreen.OTHER);
		});
		EventDelegate method_btn2 = new EventDelegate(startGameSetup);
		dia.SetButtonDelegate(method_btn, method_btn2);
	}
}
