using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Cute;
using UnityEngine;
using Wizard;
using Wizard.ErrorDialog;
using Wizard.RoomMatch;

public class Matching : MatchingBase
{
	public enum DoMatchingResult
	{
		NONE = 0,
		RC_BATTLE_MATCHING_ILLEGAL = 3001,
		RC_BATTLE_MATCHING_RETRY = 3002,
		RC_BATTLE_MATCHING_WAITING = 3003,
		RC_BATTLE_MATCHING_SUCCEEDED = 3004,
		RC_BATTLE_MATCHING_RETRY_PERIOD_ERROR = 3005,
		RC_BATTLE_MATCHING_INIT = 3006,
		RC_BATTLE_MATCHING_SUCCEEDED_OWNER = 3007,
		COLOSSEUM_BATTLE_MATCHING_RETRY = 3008,
		RC_BATTLE_MATCHING_IN_BATTLE_PHASE = 3009,
		AI_BATTLE_MATCHING_SUCCEEDED = 3011,
		COMPETITION_BATTLE_MATCHING_RETRY = 3012,
		RC_BATTLE_MATCHING_NOT_JOINED_GATHERING = 5304,
		RC_BATTLE_MATCHING_GATHERING_BATTLE_END = 5311,
		RC_BATTLE_MATCHING_NOT_ROOM_ID = 5316,
		RC_BATTLE_MATCHING_DISABLE_ROOM_ID = 5315
	}

	public enum DO_MATCHING_LOG
	{
		TEST,
		FIRST,
		RETRY,
		DEBUG
	}

	private bool _isStartBattleLoad;

	protected bool _goTitleOnTimeout;

	protected bool _receivedMatchingTimeout;

	protected int selectDeckID;

	private List<Coroutine> _doMatchingAPICoroutineList = new List<Coroutine>();

	private const int GAMESTART_MATCHING = 30;

	public const int CONNECT_TRY_COUNT = 4;

	private const int WAIT_AI_BATTLE_START = 4;

	private const int LOADED_TIMEOUT_TIMER = 25;

	protected const int CONNECT_ERROR_CODE = 12;

	public bool isDisplayCancelButton = true;

	public bool isOffViewAllEnable = true;

	private bool _isStopDoMatching;

	private bool _isDisconnect;

	private DialogBase _errorDialog;

	protected bool isGoBattle;

	private List<MatchingIntervalActionBase> _matchingIntervalActionBaseList = new List<MatchingIntervalActionBase>();

	protected MatchingRetryDomatching _retryDomatching;

	public MatchingNetworkConnectChecker _matchingNetworkConnectCheker;

	protected MatchingTimeChecker _matchingTimeCheker;

	protected MatchingRetryLoaded _matchingRetryLoaded;

	protected DoMatchingResult _doMatchingResultKind;

	private bool _isDomatchingReceiveFirstFlag;

	private int _doMatchingTimeoutPeriod;

	protected string errorDialogReturnText = Wizard.Data.SystemText.Get("Battle_0414");

	private GameObject _coroutineObject;

	private DateTime _battleStartDate;

	protected bool isOwner;

	private NetworkTask _connectAPITask;

	public bool IsStopNetWorkWithErrorCode { get; private set; }

	public MonoBehaviour CoroutineMonoBehaviour { get; private set; }

	private bool _isRecovery
	{
		get
		{
			if (BattleManagerBase.GetIns() == null || !BattleManagerBase.GetIns().IsRecovery)
			{
				return false;
			}
			return true;
		}
	}

	public Matching()
	{
		_coroutineObject = new GameObject("MatchingCoroutine");
		_coroutineObject.AddComponent<MatchingCoroutine>();
		CoroutineMonoBehaviour = _coroutineObject.GetComponent<MonoBehaviour>();
		_matchingIntervalActionBaseList = new List<MatchingIntervalActionBase>();
		_retryDomatching = new MatchingRetryDomatching(this);
		MatchingRetryDomatching retryDomatching = _retryDomatching;
		retryDomatching.OnDoMatchingSuccess = (Action)Delegate.Combine(retryDomatching.OnDoMatchingSuccess, new Action(OnFinishedDoMatching));
		_matchingIntervalActionBaseList.Add(_retryDomatching);
		_matchingNetworkConnectCheker = new MatchingNetworkConnectChecker(this);
		_matchingIntervalActionBaseList.Add(_matchingNetworkConnectCheker);
		_matchingTimeCheker = new MatchingTimeChecker(this);
		_matchingIntervalActionBaseList.Add(_matchingTimeCheker);
		_matchingRetryLoaded = new MatchingRetryLoaded(this);
		_matchingIntervalActionBaseList.Add(_matchingRetryLoaded);
		if (ToolboxGame.RealTimeNetworkAgent != null)
		{
			SettingRealTimeNetworkEvent();
			ToolboxGame.RealTimeNetworkAgent.SettingMatchingClass(this);
		}
	}

	public virtual void FirstSetting(int classId, int selDeck, bool isRecovery = false)
	{
		RealTimeNetworkAgent.FinishTaskBase = GetBattleFinishTask();
		if (ToolboxGame.RealTimeNetworkAgent != null)
		{
			ToolboxGame.RealTimeNetworkAgent.InitCurrentMatchingStatus();
		}
		if (isRecovery)
		{
			selectDeckID = selDeck;
			StartBattleLoad();
			_matchingTimeCheker.Stop();
			return;
		}
		_isStartBattleLoad = false;
		selectDeckID = selDeck;
		isOwner = false;
		_isDomatchingReceiveFirstFlag = true;
		_isStopDoMatching = false;
		_isDisconnect = false;
		DoMatching(OnFinishedDoMatching, 1, DO_MATCHING_LOG.FIRST);
		_matchingTimeCheker.Start();
		_matchingTimeCheker.SetTimeLimitSecond(30, "do_matchingTimeOut");
	}

	public void UpdateOffLineMatching()
	{
		if (ToolboxGame.RealTimeNetworkAgent == null)
		{
			UpdateMatching();
		}
	}

	public void UpdateMatching()
	{
		foreach (MatchingIntervalActionBase matchingIntervalActionBase in _matchingIntervalActionBaseList)
		{
			matchingIntervalActionBase.Update();
		}
		LocalLog.SubmitAccumulateLastTraceLog();
	}

	public void StopMatchingAction()
	{
		foreach (MatchingIntervalActionBase matchingIntervalActionBase in _matchingIntervalActionBaseList)
		{
			matchingIntervalActionBase.Stop();
		}
	}

	public override void DoMatching(Action onFinished, int need_init, DO_MATCHING_LOG log)
	{
	}

	protected void DoMatchingResultSetting()
	{
		_doMatchingResultKind = (DoMatchingResult)Wizard.Data.DoMatchingDetail.data.matchingState;
		_doMatchingTimeoutPeriod = Wizard.Data.DoMatchingDetail.data.timeoutPeriod;
		_retryDomatching.SettingRetryPeriod(Wizard.Data.DoMatchingDetail.data.retryPeriod);
		CustomPreference.SetNodeServerURL(Wizard.Data.DoMatchingDetail.data.nodeServerUrl);
	}

	protected virtual void OnFinishedDoMatching()
	{
		if (_isStopDoMatching)
		{
			return;
		}
		if (_isDomatchingReceiveFirstFlag)
		{
			_matchingTimeCheker.Start();
			_matchingTimeCheker.SetTimeLimitSecond(_doMatchingTimeoutPeriod, "do_matchingReceiveTimeOut");
			_isDomatchingReceiveFirstFlag = false;
		}
		switch (_doMatchingResultKind)
		{
		case DoMatchingResult.RC_BATTLE_MATCHING_ILLEGAL:
			ErrorDialogWithReturn(Wizard.Data.SystemText.Get("Error_3001"), Wizard.Data.SystemText.Get("ErrorHeader_3001"), Wizard.Data.SystemText.Get("Common_0132"));
			break;
		case DoMatchingResult.RC_BATTLE_MATCHING_RETRY:
		case DoMatchingResult.RC_BATTLE_MATCHING_WAITING:
		case DoMatchingResult.COLOSSEUM_BATTLE_MATCHING_RETRY:
		case DoMatchingResult.COMPETITION_BATTLE_MATCHING_RETRY:
			_retryDomatching.Start();
			_retryDomatching.SetNeedInit(0);
			break;
		case DoMatchingResult.RC_BATTLE_MATCHING_SUCCEEDED:
			StopDomatchingAPICoroutine();
			_matchingNetworkConnectCheker.SetBattleId(Wizard.Data.DoMatchingDetail.data.battleId);
			StartConnect();
			isOwner = false;
			break;
		case DoMatchingResult.RC_BATTLE_MATCHING_RETRY_PERIOD_ERROR:
			ErrorDialogWithReturn(Wizard.Data.SystemText.Get("Error_3005"), Wizard.Data.SystemText.Get("ErrorHeader_3005"), Wizard.Data.SystemText.Get("Common_0132"));
			break;
		case DoMatchingResult.RC_BATTLE_MATCHING_INIT:
			_retryDomatching.Start();
			_retryDomatching.SetNeedInit(1);
			break;
		case DoMatchingResult.RC_BATTLE_MATCHING_SUCCEEDED_OWNER:
			StopDomatchingAPICoroutine();
			_retryDomatching.SettingRetryPeriod(Wizard.Data.DoMatchingDetail.data.retryPeriod);
			_matchingNetworkConnectCheker.SetBattleId(Wizard.Data.DoMatchingDetail.data.battleId);
			StartConnect();
			isOwner = true;
			break;
		case DoMatchingResult.AI_BATTLE_MATCHING_SUCCEEDED:
			StopDomatchingAPICoroutine();
			_matchingNetworkConnectCheker.SetBattleId(Wizard.Data.DoMatchingDetail.data.battleId);
			isOwner = true;
			GameMgr.GetIns().IsAINetwork = true;
			SafeStartBattleCoroutine(CreateAIBattleStart());
			break;
		case DoMatchingResult.RC_BATTLE_MATCHING_IN_BATTLE_PHASE:
			if (ToolboxGame.RealTimeNetworkAgent == null || ToolboxGame.RealTimeNetworkAgent.CurrentMatchingStatus <= RealTimeNetworkAgent.MatchingStatus.StartLoad)
			{
				ErrorDialogWithReturn(Wizard.Data.SystemText.Get("Battle_0513"), Wizard.Data.SystemText.Get("Battle_0412"), Wizard.Data.SystemText.Get("Battle_0414"));
			}
			break;
		case (DoMatchingResult)3010:
			break;
		}
	}

	public void StartConnect()
	{
		_matchingNetworkConnectCheker.Start();
		_matchingNetworkConnectCheker.OnTimeoutInitNetwork = OnTimeoutInitNetworkToTimeOutAction;
		_matchingNetworkConnectCheker.OnConnectError = ConnectError;
	}

	private void ConnectError()
	{
		TimeOutAction("MatchingNetworkConnectCheker ConnectFailed", MatchingNetworkConnectChecker.IsOpenIpv6Dialog());
	}

	private IEnumerator CreateAIBattleStart()
	{
		yield return new WaitForSeconds(4f);
		AIBattleStartTask task = new AIBattleStartTask();
		SafeStartBattleCoroutine(Toolbox.NetworkManager.Connect(task, delegate
		{
			if (CoroutineMonoBehaviour != null)
			{
				StartConnect();
			}
		}));
	}

	private void StopDomatchingAPICoroutine()
	{
		for (int i = 0; i < _doMatchingAPICoroutineList.Count; i++)
		{
			CoroutineMonoBehaviour.StopCoroutine(_doMatchingAPICoroutineList[i]);
			_doMatchingAPICoroutineList[i] = null;
		}
		_doMatchingAPICoroutineList = new List<Coroutine>();
		Toolbox.NetworkManager.StopConnectCoroutine();
	}

	public void MatchingInitBattle()
	{
		_matchingTimeCheker.Start();
		_matchingTimeCheker.SetTimeLimitSecond(30, "matchedStart");
		ToolboxGame.RealTimeNetworkAgent.SetCurrentMatchingStatus(RealTimeNetworkAgent.MatchingStatus.Connect);
		ToolboxGame.RealTimeNetworkAgent.OnResultCodeError = ReceiveResultCodeError;
		ToolboxGame.RealTimeNetworkAgent.EmitMsgPack(GetInitBattleUri());
		if (GameMgr.GetIns().IsAINetwork)
		{
			ToolboxGame.RealTimeNetworkAgent.SetbattleId(Wizard.Data.DoMatchingDetail.data.battleId);
			StartBattleLoad();
			isGoBattle = true;
			GotoBattle();
		}
	}

	protected virtual NetworkBattleDefine.NetworkBattleURI GetInitBattleUri()
	{
		return NetworkBattleDefine.NetworkBattleURI.InitBattle;
	}

	protected override void SettingOwnerToMatchingState()
	{
	}

	protected void StartBattleLoad()
	{
		ToolboxGame.UIManager.CloseInSceneLoadingMatching();
		LoadingInScene loadingInScene = ToolboxGame.UIManager.createInSceneLoadingBattle();
		if (!_isRecovery)
		{
			loadingInScene.ProgressObj.IsOpponentWait = true;
		}
		if (_isStartBattleLoad)
		{
			return;
		}
		DataMgr dataMgr = GameMgr.GetIns().GetDataMgr();
		_isStartBattleLoad = true;
		GameMgr.GetIns().IsNetworkBattle = true;
		dataMgr.Load();
		NetworkUserInfoData networkUserInfoData = GameMgr.GetIns().GetNetworkUserInfoData();
		if (GameMgr.GetIns().IsAINetwork)
		{
			if (!_isRecovery)
			{
				GameMgr.GetIns().GetNetworkUserInfoData().TurnState = Wizard.Data.AIBattleStartData.TurnState;
				GameMgr.GetIns().SettingSelfInfo(Wizard.Data.AIBattleStartData.Data.SelfInfo.DataDictionary, isWatchReplayRecovery: false);
				GameMgr.GetIns().SettingBattleStartSelfInfo(Wizard.Data.AIBattleStartData.Data.SelfInfo.DataDictionary);
				GameMgr.GetIns().SettingOpponentInfo(Wizard.Data.AIBattleStartData.Data.OppoInfo.DataDictionary, isWatchReplayRecovery: false);
				GameMgr.GetIns().SettingBattleStartOpponentInfo(Wizard.Data.AIBattleStartData.Data.OppoInfo.DataDictionary);
				dataMgr.SetEnemySleeveId(Convert.ToInt64(Wizard.Data.AIBattleStartData.Data.OppoInfo.DataDictionary["sleeveId"]));
			}
		}
		else
		{
			long opponentSleeveId = networkUserInfoData.GetOpponentSleeveId();
			List<CardDataModel> opponentDeck = networkUserInfoData.GetOpponentDeck();
			dataMgr.SetCurrentEnemyDeckData(opponentDeck.Select((CardDataModel x) => x.CardId).ToList());
			dataMgr.SetEnemySleeveId(opponentSleeveId);
			List<CardDataModel> selfDeck = networkUserInfoData.GetSelfDeck();
			if (GameMgr.GetIns().IsWatchBattle)
			{
				ClassCharacterMasterData classCharacterMasterData = dataMgr.GetCharaPrmByCharaId(networkUserInfoData.GetSelfCharaId());
				if (classCharacterMasterData == null)
				{
					classCharacterMasterData = dataMgr.GetCharaPrmByClassId(networkUserInfoData.GetSelfClassId(), isCurrentChara: false);
				}
				dataMgr.SetPlayerCharaId(classCharacterMasterData.chara_id);
				dataMgr.SetPlayerSubClassID(networkUserInfoData.GetSelfSubClassId());
				dataMgr.SetPlayerMyRotationInfo(networkUserInfoData.GetSelfMyRotationId());
				dataMgr.SetPlayerSleeveId(networkUserInfoData.GetSelfSleeveId());
				Wizard.Data.RoomTwoPickBeforeBattleInfo.SelfInfoDeckCopyTwoPickDraftData();
			}
			dataMgr.SetCurrentDeckData(selfDeck.Select((CardDataModel x) => x.CardId).ToList());
			dataMgr.LoadEnemyClassData();
		}
		UIManager.ChangeViewSceneParam changeViewSceneParam = new UIManager.ChangeViewSceneParam();
		changeViewSceneParam.NotWait();
		if (!GameMgr.GetIns().IsReplayBattle)
		{
			changeViewSceneParam.IsInactive_AllView = false;
			changeViewSceneParam.IsDestroy_AllDialog = false;
		}
		UIManager.GetInstance().ChangeViewScene(UIManager.ViewScene.Battle, changeViewSceneParam);
		_matchingTimeCheker.Stop();
	}

	public virtual void SettingRealTimeNetworkEvent()
	{
		ToolboxGame.RealTimeNetworkAgent.OnMatchingReceiveUri = null;
		RealTimeNetworkAgent realTimeNetworkAgent = ToolboxGame.RealTimeNetworkAgent;
		realTimeNetworkAgent.OnMatchingReceiveUri = (Action<NetworkBattleDefine.NetworkBattleURI, Dictionary<string, object>>)Delegate.Combine(realTimeNetworkAgent.OnMatchingReceiveUri, new Action<NetworkBattleDefine.NetworkBattleURI, Dictionary<string, object>>(ReactionReceiveUri));
		ToolboxGame.RealTimeNetworkAgent.OnEmit = null;
		RealTimeNetworkAgent realTimeNetworkAgent2 = ToolboxGame.RealTimeNetworkAgent;
		realTimeNetworkAgent2.OnEmit = (Action<NetworkBattleDefine.NetworkBattleURI>)Delegate.Combine(realTimeNetworkAgent2.OnEmit, new Action<NetworkBattleDefine.NetworkBattleURI>(SettingLoadedTimeOutCoroutine));
	}

	private void ReactionReceiveUri(NetworkBattleDefine.NetworkBattleURI uri, Dictionary<string, object> synchronizeData)
	{
		switch (uri)
		{
		case NetworkBattleDefine.NetworkBattleURI.Matched:
			if (ToolboxGame.RealTimeNetworkAgent.CurrentMatchingStatus == RealTimeNetworkAgent.MatchingStatus.Connect)
			{
				SettingOwnerToMatchingState();
				ToolboxGame.RealTimeNetworkAgent.SetCurrentMatchingStatus(RealTimeNetworkAgent.MatchingStatus.StartLoad);
				StartBattleLoad();
			}
			break;
		case NetworkBattleDefine.NetworkBattleURI.Retry:
		{
			string value = synchronizeData[NetworkBattleDefine.NetworkParameterNames[NetworkBattleDefine.NetworkParameter.targetUri]].ToString();
			if (Enum.IsDefined(typeof(NetworkBattleDefine.NetworkBattleURI), value) && (NetworkBattleDefine.NetworkBattleURI)Enum.Parse(typeof(NetworkBattleDefine.NetworkBattleURI), value) == NetworkBattleDefine.NetworkBattleURI.Loaded)
			{
				_matchingRetryLoaded.Start();
			}
			break;
		}
		case NetworkBattleDefine.NetworkBattleURI.BattleStart:
			if (synchronizeData.ContainsKey(NetworkBattleDefine.NetworkParameterNames[NetworkBattleDefine.NetworkParameter.battleStartDate]))
			{
				_battleStartDate = TimeUtil.MicroTimeToFromUnixTime(long.Parse(synchronizeData[NetworkBattleDefine.NetworkParameterNames[NetworkBattleDefine.NetworkParameter.battleStartDate]].ToString()));
			}
			else
			{
				_battleStartDate = DateTime.Now;
			}
			ToolboxGame.RealTimeNetworkAgent.SetNetworkInfo(synchronizeData, ref uri);
			ToolboxGame.RealTimeNetworkAgent.SetCurrentMatchingStatus(RealTimeNetworkAgent.MatchingStatus.Prepared);
			SafeStartBattleCoroutine(CheckNetworkInfo(delegate
			{
				isGoBattle = true;
				_matchingTimeCheker.Stop();
				GotoBattle();
			}));
			break;
		}
	}

	private IEnumerator CheckNetworkInfo(Action callback)
	{
		while (!BattleManagerBase.GetIns().BattleStartControl.IsReady)
		{
			yield return null;
		}
		callback.Call();
	}

	private void SettingLoadedTimeOutCoroutine(NetworkBattleDefine.NetworkBattleURI uri)
	{
		if (uri == NetworkBattleDefine.NetworkBattleURI.Loaded)
		{
			_goTitleOnTimeout = true;
			_matchingTimeCheker.Start();
			_matchingTimeCheker.SetTimeLimitSecond(25, "loadedTimeout");
			RealTimeNetworkAgent realTimeNetworkAgent = ToolboxGame.RealTimeNetworkAgent;
			realTimeNetworkAgent.OnEmit = (Action<NetworkBattleDefine.NetworkBattleURI>)Delegate.Remove(realTimeNetworkAgent.OnEmit, new Action<NetworkBattleDefine.NetworkBattleURI>(SettingLoadedTimeOutCoroutine));
		}
	}

	private void RemoveRealTimeNetworkEvent()
	{
		ToolboxGame.RealTimeNetworkAgent.OnMatchingReceiveUri = null;
		ToolboxGame.RealTimeNetworkAgent.OnEmit = null;
		_matchingNetworkConnectCheker.OnConnectError = null;
		_matchingNetworkConnectCheker.OnTimeoutInitNetwork = null;
	}

	public virtual void GotoBattle()
	{
		SettingOpponentClassDataAndLoadObject();
		RemoveRealTimeNetworkEvent();
		if (!GameMgr.GetIns().IsAINetwork)
		{
			BattleManagerBase.GetIns().SetupReplayBattleInfoFilter();
		}
		if ((bool)ToolboxGame.RealTimeNetworkAgent && ToolboxGame.RealTimeNetworkAgent.CurrentMatchingStatus != RealTimeNetworkAgent.MatchingStatus.Prepared)
		{
			ToolboxGame.RealTimeNetworkAgent.SetCurrentMatchingStatus(RealTimeNetworkAgent.MatchingStatus.Prepared);
		}
		if (!GameMgr.GetIns().IsAINetwork)
		{
			if ((bool)ToolboxGame.RealTimeNetworkAgent)
			{
				NetworkBattleManagerBase networkBattleManagerBase = BattleManagerBase.GetIns() as NetworkBattleManagerBase;
				networkBattleManagerBase.SettingOpponentAliveEvent();
				if (!_isRecovery)
				{
					networkBattleManagerBase.IsStopIntervalCheck = false;
				}
				ToolboxGame.RealTimeNetworkAgent.StartPreparedStartTimer(_battleStartDate);
				ToolboxGame.RealTimeNetworkAgent.StartRecoveryRecording();
			}
			UIManager.GetInstance().OffViewAllOutside(UIManager.ViewScene.Battle);
			if (!_isRecovery)
			{
				ToolboxGame.UIManager.CloseInSceneLoadingBattle();
			}
		}
		DestroyCoroutineObject();
	}

	protected void SettingOpponentClassDataAndLoadObject()
	{
		DataMgr dataMgr = GameMgr.GetIns().GetDataMgr();
		NetworkUserInfoData networkUserInfoData = GameMgr.GetIns().GetNetworkUserInfoData();
		ClassCharacterMasterData classCharacterMasterData = dataMgr.GetCharaPrmByCharaId(networkUserInfoData.GetOpponentCharaId());
		bool flag = PlayerPrefsWrapper.GetBool(PlayerPrefsWrapper.SHOW_OPPONENT_DEFAULT_SKIN);
		if (flag && networkUserInfoData.GetOpponentChaosId() != -1 && (GameMgr.GetIns().IsNetworkBattle || GameMgr.GetIns().IsReplayBattle) && !networkUserInfoData.GetOpponentChaosOverrideSkin())
		{
			flag = false;
		}
		if (classCharacterMasterData == null || flag)
		{
			classCharacterMasterData = dataMgr.GetCharaPrmByClassId(networkUserInfoData.GetOpponentClassId(), isCurrentChara: false);
		}
		dataMgr.SetEnemyCharaId(classCharacterMasterData.chara_id);
		dataMgr.SetEnemySubClassID(networkUserInfoData.GetOpponentSubClassId());
		dataMgr.SetEnemyMyRotationInfo(networkUserInfoData.GetOpponentMyRotationId());
		dataMgr.SetEnemyAvatarBattleInfo(networkUserInfoData.GetOpponentAvatarBattleId());
	}

	public virtual FinishTaskBase GetBattleFinishTask()
	{
		return new FinishTaskBase();
	}

	public bool GetMatchingDataReady()
	{
		return _isStartBattleLoad;
	}

	public void DisConnect(Action onDisconnected)
	{
		if (!_isDisconnect)
		{
			_isDisconnect = true;
			string text = "matchingDisconnect";
			DestroyCoroutineObject();
			if ((bool)ToolboxGame.RealTimeNetworkAgent)
			{
				text += ToolboxGame.RealTimeNetworkAgent.CurrentMatchingStatus;
				ToolboxGame.RealTimeNetworkAgent.DestroyObj(RealTimeNetworkAgent.DESTROY_OBJECT_LOG.MatchingDisconnect);
			}
			text += StackTraceUtility.ExtractStackTrace();
			LocalLog.AccumulateLastTraceLog(text);
			_isStopDoMatching = true;
			onDisconnected.Call();
		}
	}

	protected void DestroyCoroutineObject()
	{
		StopMatchingAction();
		if (CoroutineMonoBehaviour != null)
		{
			CoroutineMonoBehaviour.StopAllCoroutines();
			CoroutineMonoBehaviour = null;
		}
		if (_coroutineObject != null)
		{
			UnityEngine.Object.Destroy(_coroutineObject);
			_coroutineObject = null;
		}
	}

	public void ReturnScene()
	{
		if (!_isStartBattleLoad && isOffViewAllEnable)
		{
			UIManager.GetInstance().OffViewAll();
		}
		ToolboxGame.DestroyNetworkAgent();
		GameMgr.GetIns().IsAINetwork = false;
		if (GetMatchingDataReady() && GameMgr.GetIns().GetBattleCtrl() != null)
		{
			UIManager.GetInstance().StartCoroutine(BattleEndCoroutin(GotoHomeScene));
			return;
		}
		UIManager.GetInstance().CloseInSceneLoadingMatching();
		if (GetMatchingDataReady())
		{
			GotoHomeScene();
		}
		else
		{
			GotoDeckSelectScene();
		}
	}

	protected virtual void GotoHomeScene()
	{
		UIManager.ChangeViewSceneParam changeViewSceneParam = new UIManager.ChangeViewSceneParam();
		changeViewSceneParam.MyPageMenuIndex = 0;
		changeViewSceneParam.IsCutCardMotion = true;
		UIManager.GetInstance().CloseInSceneLoadingMatching();
		UIManager.GetInstance().CloseInSceneLoadingBattle();
		UIManager.GetInstance().ChangeViewScene(UIManager.ViewScene.MyPage, changeViewSceneParam);
	}

	protected override void GotoDeckSelectScene()
	{
	}

	private void OnSelectDeck(DialogBase dialogDeckList, DeckData deck)
	{
		if (deck == null || GameMgr.GetIns().GetDataMgr().m_BattleType == DataMgr.BattleType.None)
		{
			return;
		}
		if (!deck.IsUsable())
		{
			InCompleteDeckDecideDialog.Create(dialogDeckList, deck);
			return;
		}
		CompleteDeckDecideDialog completeDeckDecideDialog = CompleteDeckDecideDialog.CreateForSingleDeck(dialogDeckList, deck, showSimpleStageOption: false, null);
		if (GameMgr.GetIns().GetDataMgr().m_BattleType == DataMgr.BattleType.RoomBattle || GameMgr.GetIns().GetDataMgr().m_BattleType == DataMgr.BattleType.RoomTwoPick)
		{
			RoomBase.DeckConfirmDialog = completeDeckDecideDialog.Dialog;
		}
	}

	public void QuitMatching(bool isReturnScene = true)
	{
		if (ToolboxGame.RealTimeNetworkAgent != null)
		{
			LocalLog.AccumulateLastTraceLog("Matching_QuitMatching" + ToolboxGame.RealTimeNetworkAgent.CurrentMatchingStatus);
		}
		DisConnect(delegate
		{
			if (isReturnScene)
			{
				ReturnScene();
			}
		});
	}

	public void ReceiveResultCodeError(int code)
	{
		if (!IsStopNetWorkWithErrorCode)
		{
			IsStopNetWorkWithErrorCode = true;
			_matchingTimeCheker.Stop();
			switch (code)
			{
			case 30201:
				_receivedMatchingTimeout = true;
				TimeOutAction("ReceiveResultCodeError");
				break;
			case 30212:
				TimeOutAction("NodeErrorDisconnect");
				break;
			case 30001:
			case 30002:
			case 30213:
			case 30302:
				DisConnect(null);
				break;
			}
		}
	}

	private void OnTimeoutInitNetworkToTimeOutAction()
	{
		_matchingNetworkConnectCheker.OnTimeoutInitNetwork = null;
		TimeOutAction("OnTimeoutInitNetwork");
	}

	public virtual void TimeOutAction(string log, bool isIpv6Dialog = false)
	{
		LocalLog.AccumulateLastTraceLog("TimeOutAction " + log);
		if (ToolboxGame.RealTimeNetworkAgent != null && ToolboxGame.RealTimeNetworkAgent.CurrentMatchingStatus >= RealTimeNetworkAgent.MatchingStatus.Prepared && ToolboxGame.RealTimeNetworkAgent.CurrentMatchingStatus != RealTimeNetworkAgent.MatchingStatus.RoomReady && ToolboxGame.RealTimeNetworkAgent.CurrentMatchingStatus != RealTimeNetworkAgent.MatchingStatus.Room)
		{
			LocalLog.AccumulateLastTraceLog("Matching_TimeOutActionIgnore" + ToolboxGame.RealTimeNetworkAgent.CurrentMatchingStatus);
		}
		else if (isIpv6Dialog)
		{
			ErrorDialogWithRetry("", Wizard.Data.SystemText.Get("ErrorHeader_0016"), isIpv6Dialog);
		}
		else if (_goTitleOnTimeout && !_receivedMatchingTimeout)
		{
			ErrorDialogGoToTitle(Wizard.Data.SystemText.Get("Battle_0508"), Wizard.Data.SystemText.Get("Battle_0412"));
		}
		else if (_isStartBattleLoad || _receivedMatchingTimeout)
		{
			ErrorDialogWithReturn(Wizard.Data.SystemText.Get("Battle_0404"), Wizard.Data.SystemText.Get("Battle_0412"), Wizard.Data.SystemText.Get("Common_0132"));
		}
		else
		{
			TimeOutMessageToRetry();
		}
	}

	protected virtual void TimeOutMessageToRetry()
	{
		if (ToolboxGame.RealTimeNetworkAgent != null)
		{
			LocalLog.AccumulateLastTraceLog("Matching_TimeOutMessageToRetry" + ToolboxGame.RealTimeNetworkAgent.CurrentMatchingStatus);
		}
		ErrorDialogWithRetry(Wizard.Data.SystemText.Get("Battle_0405"), Wizard.Data.SystemText.Get("Battle_0412"));
	}

	protected int GetLastResultCode()
	{
		return _connectAPITask.GetResultCode();
	}

	protected void ConnectAPI(NetworkTask task, Action<NetworkTask.ResultCode> callbackOnSuccess = null)
	{
		string text = "Matching_ConnectAPI " + task;
		if ((bool)ToolboxGame.RealTimeNetworkAgent)
		{
			text += ToolboxGame.RealTimeNetworkAgent.CurrentMatchingStatus;
		}
		text += StackTraceUtility.ExtractStackTrace();
		LocalLog.AccumulateLastTraceLog(text);
		_connectAPITask = task;
		task.SkipAllCuteResultCodeCheckErrorPopup();
		task.SkipCuteTimeOutPopup();
		task.SkipCuteHttpStatusErrorPopup();
		_doMatchingAPICoroutineList.Add(SafeStartBattleCoroutine(Toolbox.NetworkManager.Connect(task, callbackOnSuccess, delegate(NetworkTask.ResultCode result)
		{
			if (task.GetResultCode() == 109)
			{
				LocalLog.AccumulateLastTraceLog("Matching_TimeSlipRotation SeasonChangeError");
				Dialog.Create(task.GetResultCode());
			}
			else
			{
				OnFailed((int)result);
			}
		}, OnErrorAPI)));
	}

	protected virtual void OnFailed(int code)
	{
		string text = "Matching_ConnectAPIOnFailed";
		if (ToolboxGame.RealTimeNetworkAgent != null)
		{
			text += ToolboxGame.RealTimeNetworkAgent.CurrentMatchingStatus;
		}
		LocalLog.AccumulateLastTraceLog(text);
		int num = code;
		if (code == 4)
		{
			UIManager.GetInstance().closeInSceneLoading();
			DisConnect(null);
		}
		else
		{
			num = 12;
			OnErrorAPI(num);
		}
	}

	private void OnErrorAPI(int code)
	{
		if (code == 9999)
		{
			DisConnect(delegate
			{
				Dialog.Create(code);
			});
		}
		else
		{
			if (_connectAPITask != null && _connectAPITask.GetResultCode() == 109)
			{
				return;
			}
			string text = "Matching_OnErrorAPI";
			if (ToolboxGame.RealTimeNetworkAgent != null)
			{
				text += ToolboxGame.RealTimeNetworkAgent.CurrentMatchingStatus;
			}
			LocalLog.AccumulateLastTraceLog(text);
			UIManager.GetInstance().closeInSceneLoading();
			TaskManager.GetErrorMsgFromCode(code, out var msg, out var title);
			if (code != 317)
			{
				bool num = code == 101 || (code >= 2000 && code <= 2999);
				bool flag = code >= 2000 && code <= 2999;
				if (num)
				{
					NetworkUI.GetInstance().OpenGoToTitleErrorPopUp(title, Wizard.Data.SystemText.Get("Battle_0409"), code.ToString());
				}
				else if (flag)
				{
					ErrorDialogWithReturn(msg, title, Wizard.Data.SystemText.Get("Common_0132"));
				}
				else if (code == 3010)
				{
					ErrorDialogGoToTitle(msg, title);
				}
				else
				{
					ErrorDialogWithRetry(msg, title);
				}
			}
		}
	}

	protected DialogBase CreateDialogBase()
	{
		DialogBase dialogBase = null;
		return (_errorDialog != null) ? _errorDialog : (_errorDialog = UIManager.GetInstance().CreateDialogClose());
	}

	protected void ErrorDialogWithReturn(string text, string title, string buttonMsg)
	{
		DisConnect(delegate
		{
			DialogBase dialogBase = CreateDialogBase();
			dialogBase.SetTitleLabel(title);
			dialogBase.SetText(text);
			dialogBase.SetButtonLayout(DialogBase.ButtonLayout.GrayBtn);
			dialogBase.SetButtonText(buttonMsg);
			dialogBase.SetFadeButtonEnabled(flag: false);
			dialogBase.SetPanelDepth(5400);
			dialogBase.OnClose = ReturnScene;
		});
	}

	protected void ErrorDialogGoToTitle(string text, string title)
	{
		DisConnect(delegate
		{
			DialogBase dialogBase = CreateDialogBase();
			dialogBase.SetTitleLabel(title);
			dialogBase.SetText(text);
			dialogBase.SetButtonLayout(DialogBase.ButtonLayout.BackToTitleBtn);
			dialogBase.SetFadeButtonEnabled(flag: false);
			dialogBase.SetPanelDepth(5400);
		});
	}

	protected void ErrorDialogWithRetry(string text, string title, bool isIpv6Dialog = false)
	{
		DisConnect(delegate
		{
			ErrorDialog(text, title, isIpv6Dialog);
		});
	}

	protected virtual void ErrorDialog(string text, string title, bool isIPv6Dialog)
	{
		DialogBase dialogBase = CreateDialogBase();
		if (isIPv6Dialog)
		{
			MatchingIPv6Toggle.AddMatchingIPv6Toggle(dialogBase);
		}
		dialogBase.SetSize(DialogBase.Size.M);
		dialogBase.SetTitleLabel(title);
		dialogBase.SetText(text);
		dialogBase.SetButtonLayout(DialogBase.ButtonLayout.BlueBtn_GrayBtn);
		dialogBase.SetButtonText(Wizard.Data.SystemText.Get("System_0012"), errorDialogReturnText);
		dialogBase.SetFadeButtonEnabled(flag: false);
		dialogBase.SetPanelDepth(5400);
		dialogBase.ClickSe_Btn2 = Se.TYPE.SYS_BTN_CANCEL_TRANS;
		EventDelegate method_btn = new EventDelegate(delegate
		{
			ToolboxGame.DestroyNetworkAgent();
			Action action = delegate
			{
				UIManager.ChangeViewSceneParam param = new UIManager.ChangeViewSceneParam
				{
					OnChange = delegate
					{
						UIManager.GetInstance().CloseInSceneLoadingBattle();
					}
				};
				UIManager.GetInstance().ChangeViewScene(UIManager.ViewScene.RankMatch, param);
			};
			if (_isStartBattleLoad)
			{
				UIManager.GetInstance().StartCoroutine(BattleEndCoroutin(action));
			}
			else
			{
				action();
			}
		});
		EventDelegate eventDelegate = new EventDelegate(ReturnScene);
		dialogBase.SetButtonDelegate(method_btn, eventDelegate, eventDelegate, eventDelegate);
	}

	protected IEnumerator BattleEndCoroutin(Action callback)
	{
		yield return null;
		SBattleLoad battleLoad = BattleManagerBase.GetIns().SBattleLoad;
		while (!battleLoad.isLoadEnd)
		{
			yield return null;
		}
		yield return GameMgr.GetIns().GetBattleCtrl().BattleEnd();
		callback();
	}

	public Coroutine SafeStartBattleCoroutine(IEnumerator routine)
	{
		if (CoroutineMonoBehaviour == null)
		{
			return null;
		}
		return CoroutineMonoBehaviour.StartCoroutine(routine);
	}
}
