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

namespace Wizard;

public class GatheringTournament : MonoBehaviour
{
	private enum DoubleTab
	{
		Winners,
		Losers
	}

	[SerializeField]
	private GameObject _originalTournament;

	[SerializeField]
	private GameObject _tournamentRoot;

	[SerializeField]
	private UILabel _ruleLabel;

	[SerializeField]
	private GameObject _singleRoot;

	[SerializeField]
	private GameObject _doubleRoot;

	[SerializeField]
	private UIButton _winnersButton;

	[SerializeField]
	private UIButton _losersButton;

	[SerializeField]
	private GameObject _messageRoot;

	[SerializeField]
	private UILabel _messageLabel;

	private List<TournamentController> _tournamentControllers;

	private List<TournamentData> _tournamentDataList;

	private List<string> _resourceList;

	private DoubleTab _doubleTab;

	public void Show(GatheringInfo info, GatheringJoining parent)
	{
		UIManager.GetInstance().AttachAtlas(base.gameObject);
		_originalTournament.SetActive(value: false);
		_singleRoot.SetActive(value: false);
		_doubleRoot.SetActive(value: false);
		_ruleLabel.text = RoomRuleSetting.GetWinTypeString(info.Rule.BattleParameterInstance.Rule) + "  " + FormatBehaviorManager.GetFormatName(info.Rule.BattleParameterInstance.DeckFormat);
		GatheringGetSelfInfoTask task = new GatheringGetSelfInfoTask(isDependGatheringInfo: true);
		StartCoroutine(Toolbox.NetworkManager.Connect(task, delegate
		{
			GatheringTournamentInfoTask tournamentInfoTask = new GatheringTournamentInfoTask();
			StartCoroutine(Toolbox.NetworkManager.Connect(tournamentInfoTask, delegate
			{
				if (tournamentInfoTask.TournamentDataList != null)
				{
					Setup(tournamentInfoTask.TournamentDataList, info);
				}
				else
				{
					SetMessage(Data.SystemText.Get("Gathering_Tournament_0009"));
				}
			}));
		}));
	}

	private void Setup(List<TournamentData> tournamentDataList, GatheringInfo info)
	{
		_tournamentDataList = tournamentDataList;
		_tournamentRoot.SetActive(value: true);
		_messageRoot.SetActive(value: false);
		bool flag = !info.OwnerInfo.IsSelf || info.Rule.IsOwnerEntryBattle;
		_doubleTab = GetCurrentTabAndCell(out var currentCells, tournamentDataList, flag);
		if (flag && currentCells.All((TournamentCellData c) => c == null))
		{
			_doubleTab = GetCurrentTabAndCell(out currentCells, tournamentDataList, isEntry: false);
		}
		SetupTournamentType(info.Rule.TournamentType);
		_resourceList = CollectResourcePath(tournamentDataList);
		StartCoroutine(Toolbox.ResourcesManager.LoadAssetGroupAsync(_resourceList, delegate
		{
			_originalTournament.SetActive(value: true);
			_tournamentControllers = new List<TournamentController>(tournamentDataList.Count);
			for (int i = 0; i < tournamentDataList.Count; i++)
			{
				TournamentController componentInChildren = NGUITools.AddChild(_tournamentRoot, _originalTournament).GetComponentInChildren<TournamentController>();
				_tournamentControllers.Add(componentInChildren);
				StartCoroutine(componentInChildren.Setup(tournamentDataList[i], currentCells[i], info, i == (int)_doubleTab));
			}
			_originalTournament.SetActive(value: false);
		}));
	}

	private void SetupTournamentType(GatheringRule.eTournamentType type)
	{
		_singleRoot.SetActive(type == GatheringRule.eTournamentType.SINGLE_ELIMINATION);
		_doubleRoot.SetActive(type == GatheringRule.eTournamentType.DOUBLE_ELIMINATION);
		_winnersButton.onClick.Add(new EventDelegate(delegate
		{
			GameMgr.GetIns().GetSoundMgr().PlaySe(Se.TYPE.SYS_BTN_DECIDE);
			SetDoubleTab(DoubleTab.Winners);
		}));
		_losersButton.onClick.Add(new EventDelegate(delegate
		{
			GameMgr.GetIns().GetSoundMgr().PlaySe(Se.TYPE.SYS_BTN_DECIDE);
			SetDoubleTab(DoubleTab.Losers);
		}));
		UpdateDoubleTab();
	}

	private DoubleTab GetCurrentTabAndCell(out List<TournamentCellData> currentCells, List<TournamentData> tournamentDataList, bool isEntry)
	{
		currentCells = new List<TournamentCellData>(tournamentDataList.Count);
		foreach (TournamentData tournamentData in tournamentDataList)
		{
			bool flag = false;
			for (int num = tournamentData.Rounds.Count - 1; num >= 0; num--)
			{
				foreach (TournamentCellData cell in tournamentData.Rounds[num].Cells)
				{
					if (IsCurrentCell(cell))
					{
						currentCells.Add(cell);
						flag = true;
						break;
					}
				}
				if (flag)
				{
					break;
				}
			}
			if (!flag)
			{
				currentCells.Add(null);
			}
		}
		if (currentCells.Count > 1)
		{
			if (currentCells[0] == null)
			{
				return DoubleTab.Winners;
			}
			if (currentCells[0].Round == tournamentDataList[0].Rounds[tournamentDataList[0].Rounds.Count - 2])
			{
				return DoubleTab.Winners;
			}
			if (currentCells[0].State != TournamentCellData.CellState.Lose || currentCells[1] == null)
			{
				return DoubleTab.Winners;
			}
			return DoubleTab.Losers;
		}
		return DoubleTab.Winners;
		bool IsCurrentCell(TournamentCellData targetCell)
		{
			if (targetCell == null)
			{
				return false;
			}
			TournamentCellData.CellState state = targetCell.State;
			if (state == TournamentCellData.CellState.Unresolved || state == TournamentCellData.CellState.Active || state == TournamentCellData.CellState.Win || state == TournamentCellData.CellState.Lose)
			{
				if (isEntry)
				{
					return targetCell.ViewerId == PlayerStaticData.UserViewerID;
				}
				return true;
			}
			return false;
		}
	}

	private void UpdateDoubleTab()
	{
		_winnersButton.normalSprite = ((_doubleTab == DoubleTab.Winners) ? "pilltab_02_left_on" : "pilltab_02_left_off");
		_losersButton.normalSprite = ((_doubleTab == DoubleTab.Losers) ? "pilltab_02_right_on" : "pilltab_02_right_off");
	}

	private void SetDoubleTab(DoubleTab tab)
	{
		if (_doubleTab != tab)
		{
			_doubleTab = tab;
			UpdateDoubleTab();
			for (int i = 0; i < _tournamentControllers.Count; i++)
			{
				_tournamentControllers[i].SetVisible(i == (int)tab);
			}
		}
	}

	private List<string> CollectResourcePath(List<TournamentData> dataList)
	{
		List<string> resourceList = new List<string>();
		foreach (TournamentData data in dataList)
		{
			data.CollectResourcePath(ref resourceList);
		}
		return resourceList;
	}

	private void OnDestroy()
	{
		if (_resourceList != null)
		{
			Toolbox.ResourcesManager.RemoveAssetGroup(_resourceList);
			_resourceList.Clear();
		}
	}

	private void SetMessage(string message)
	{
		_tournamentRoot.SetActive(value: false);
		_messageRoot.SetActive(value: true);
		_messageLabel.text = message;
	}
}
