using System;
using System.Collections.Generic;
using System.Linq;
using Cute;
using UnityEngine;
using Wizard.DeckSelect.FirstDisplayPageIndexGetter;

namespace Wizard;

public class DeckSelectUI : MonoBehaviour
{
	public class InitOptions
	{
		public Action<DeckUI> OnUpdateDeckUICustomize { get; set; }

		public Action OnClickInfoButton { get; set; }

		public DeckData PrimaryFirstDisplayDeck { get; set; }

		public bool CanUseNonPossessionCard { get; set; }

		public IFirstDisplayPageIndexGetter FirstDisplayPageIndexGetter { get; set; }

		public int? LongTextTitlePosition { get; set; }
	}

	private enum ChangeMoveDirection
	{
		NONE,
		RIGHT,
		LEFT
	}

	public class PageData
	{
		public Format Format { get; private set; }

		public DeckAttributeType AttributeType { get; private set; }

		public string GroupName { get; private set; }

		public List<DeckUI.DeckViewData> DeckViewList { get; private set; }

		public static List<PageData> CreatePageList(List<DeckGroup> deckGroupList, bool isVisibleCreateNew)
		{
			List<PageData> list = new List<PageData>();
			foreach (DeckGroup deckGroup in deckGroupList)
			{
				List<DeckUI.DeckViewData> list2 = DeckUI.DeckViewData.CreateDeckViewList(deckGroup.DeckDataList, isVisibleCreateNew);
				if (!list2.Any((DeckUI.DeckViewData d) => d.ViewType != DeckUI.eViewType.Empty))
				{
					continue;
				}
				int num = 0;
				for (int num2 = 0; num2 < list2.Count; num2++)
				{
					if (num2 % 9 == 0)
					{
						if (list2[num2].ViewType == DeckUI.eViewType.Empty)
						{
							break;
						}
						num++;
						string groupName = DeckListUtility.DeckListHeader(deckGroup.AttributeType, num);
						list.Add(new PageData(new List<DeckUI.DeckViewData>(), deckGroup.DeckFormat, deckGroup.AttributeType, groupName));
					}
					list.Last().AddDeckViewList(list2[num2]);
				}
			}
			return list;
		}

		private PageData(List<DeckUI.DeckViewData> deckViewList, Format format, DeckAttributeType attributeType, string groupName)
		{
			DeckViewList = deckViewList;
			Format = format;
			AttributeType = attributeType;
			GroupName = groupName;
		}

		private void AddDeckViewList(DeckUI.DeckViewData deckViewData)
		{
			DeckViewList.Add(deckViewData);
		}
	}

	private class DeckTable
	{
		private List<DeckUI> _deckUIList = new List<DeckUI>();

		private Action<DeckUI> _onUpdateDeckUICustomize;

		public GameObject Obj { get; private set; }

		public DeckTable(UIGrid uiGrid, DeckUI originalDeckUI, Action<DeckUI> onClick, Action<Vector2> onDrag, Action<DeckUI> onUpdateDeckUICustomize)
		{
			_onUpdateDeckUICustomize = onUpdateDeckUICustomize;
			for (int i = 0; i < 9; i++)
			{
				DeckUI component = NGUITools.AddChild(uiGrid.gameObject, originalDeckUI.gameObject).GetComponent<DeckUI>();
				component.Initialize(onClick);
				UIEventListener uIEventListener = UIEventListener.Get(component.gameObject);
				uIEventListener.onDrag = (UIEventListener.VectorDelegate)Delegate.Combine(uIEventListener.onDrag, (UIEventListener.VectorDelegate)delegate(GameObject g, Vector2 v)
				{
					onDrag.Call(v);
				});
				_deckUIList.Add(component);
				component.gameObject.SetActive(value: false);
			}
			uiGrid.repositionNow = true;
			Obj = uiGrid.gameObject;
			Obj.SetActive(value: true);
		}

		public void UpdateDeckViewList(List<DeckUI.DeckViewData> deckViewList, bool canUseNonPossessionCard)
		{
			for (int i = 0; i < _deckUIList.Count; i++)
			{
				if (deckViewList.Count > i)
				{
					DeckUI deckUI = _deckUIList[i];
					deckUI.gameObject.SetActive(value: true);
					deckUI.UpdateView(deckViewList[i], canUseNonPossessionCard);
					_onUpdateDeckUICustomize.Call(deckUI);
				}
				else
				{
					_deckUIList[i].gameObject.SetActive(value: false);
				}
			}
		}
	}

	private const int MAXNUM_DECK_PER_TABLE = 9;

	private const float DRAG_DEGREE = 70f;

	private const float PAGE_INTERVAL = 1400f;

	private const float MOVE_PAGE_DURATION = 0.2f;

	private static readonly Vector3 VIEW_PAGE_POSITION = Vector3.zero;

	private static readonly Vector3 OUTSIDE_RIGHT_PAGE_POSITION = VIEW_PAGE_POSITION + Vector3.right * 1400f;

	private static readonly Vector3 OUTSIDE_LEFT_PAGE_POSITION = VIEW_PAGE_POSITION + Vector3.left * 1400f;

	[SerializeField]
	private DeckUI _deckFrameOriginal;

	[SerializeField]
	private UILabel _titleLabel;

	[SerializeField]
	private GameObject _deckTableRoot;

	[SerializeField]
	private UIPageIndicator _pageIndicatorOriginal;

	private UIPageIndicator _pageIndicator;

	[SerializeField]
	private GameObject _pageIndicatorRoot;

	[SerializeField]
	private UIButton _leftButton;

	[SerializeField]
	private UIButton _rightButton;

	[SerializeField]
	private BoxCollider _flickCollider;

	[SerializeField]
	private UILabel _noDeckText;

	[SerializeField]
	private UILabel _cautionLabel;

	[SerializeField]
	private UIGrid[] _deckTableGrids = new UIGrid[2];

	[SerializeField]
	private UIPanel _panel;

	[SerializeField]
	private UIButton _infoButton;

	private DeckTable[] _deckTables = new DeckTable[2];

	private int _deckTableIndex;

	private Action<DeckData> OnSelectDeck;

	private Action<Format> OnChangePage;

	private bool _isOnDestroy;

	private List<string> _resourcePathList;

	private int _currentPageIndex;

	private List<PageData> _pageList;

	private bool _isInitialized;

	private bool _canUseNonPossessionCard;

	public bool IsPageMoving { get; private set; }

	public void Initialize(List<DeckGroup> deckGroupList, Format format, bool isVisibleCreateNew, Action<DeckData> onSelectDeck, Action<Format> onChangePage, Action onInitializeFinish, InitOptions initOptions = null)
	{
		if (initOptions == null)
		{
			initOptions = new InitOptions();
		}
		_infoButton.gameObject.SetActive(initOptions.OnClickInfoButton != null);
		_canUseNonPossessionCard = initOptions.CanUseNonPossessionCard;
		UIEventListener uIEventListener = UIEventListener.Get(_flickCollider.gameObject);
		uIEventListener.onDrag = (UIEventListener.VectorDelegate)Delegate.Combine(uIEventListener.onDrag, (UIEventListener.VectorDelegate)delegate(GameObject g, Vector2 v)
		{
			OnDragPanel(v);
		});
		UIEventListener uIEventListener2 = UIEventListener.Get(_rightButton.gameObject);
		uIEventListener2.onClick = (UIEventListener.VoidDelegate)Delegate.Combine(uIEventListener2.onClick, (UIEventListener.VoidDelegate)delegate
		{
			NextPage();
		});
		UIEventListener uIEventListener3 = UIEventListener.Get(_leftButton.gameObject);
		uIEventListener3.onClick = (UIEventListener.VoidDelegate)Delegate.Combine(uIEventListener3.onClick, (UIEventListener.VoidDelegate)delegate
		{
			PrevPage();
		});
		if (initOptions.OnClickInfoButton != null)
		{
			UIEventListener uIEventListener4 = UIEventListener.Get(_infoButton.gameObject);
			uIEventListener4.onClick = (UIEventListener.VoidDelegate)Delegate.Combine(uIEventListener4.onClick, (UIEventListener.VoidDelegate)delegate
			{
				GameMgr.GetIns().GetSoundMgr().PlaySe(Se.TYPE.SYS_COMMON_BUTTON);
				initOptions.OnClickInfoButton.Call();
			});
		}
		OnSelectDeck = onSelectDeck;
		OnChangePage = onChangePage;
		_deckTables[0] = new DeckTable(_deckTableGrids[0], _deckFrameOriginal, OnClickDeck, OnDragPanel, initOptions.OnUpdateDeckUICustomize);
		_deckTables[1] = new DeckTable(_deckTableGrids[1], _deckFrameOriginal, OnClickDeck, OnDragPanel, initOptions.OnUpdateDeckUICustomize);
		_cautionLabel.gameObject.SetActive(value: false);
		Action onSettingDeckListFinish = delegate
		{
			_isInitialized = true;
			onInitializeFinish.Call();
		};
		UpdateDeckView(deckGroupList, format, isVisibleCreateNew, onSettingDeckListFinish, initOptions.PrimaryFirstDisplayDeck, initOptions.FirstDisplayPageIndexGetter);
	}

	public void UpdateDeckView(List<DeckGroup> deckGroupList, Format format, bool isVisibleCreateNew, Action onSettingDeckListFinish = null, DeckData primaryFirstDisplayDeck = null, IFirstDisplayPageIndexGetter firstDisplayPageIndexGetter = null)
	{
		List<DeckData> list = new List<DeckData>();
		foreach (DeckGroup deckGroup in deckGroupList)
		{
			list.AddRange(deckGroup.DeckDataList);
		}
		LoadResources(list, delegate
		{
			if (!_isOnDestroy)
			{
				if (firstDisplayPageIndexGetter == null)
				{
					firstDisplayPageIndexGetter = new DefaultFirstDisplayPageIndexGetter();
				}
				CreateDeckGroupPages(deckGroupList, isVisibleCreateNew, format, primaryFirstDisplayDeck, firstDisplayPageIndexGetter);
				onSettingDeckListFinish.Call();
			}
		});
	}

	public void ShowCautionText(string cautionText)
	{
		_cautionLabel.gameObject.SetActive(cautionText != string.Empty);
		_cautionLabel.text = cautionText;
	}

	public void UpdateAllDeckUICurrentPage()
	{
		_deckTables[_deckTableIndex].UpdateDeckViewList(_pageList[_currentPageIndex].DeckViewList, _canUseNonPossessionCard);
	}

	private void OnClickDeck(DeckUI deckUI)
	{
		GameMgr.GetIns().GetSoundMgr().PlaySe(Se.TYPE.SYS_COMMON_BUTTON);
		OnSelectDeck.Call(deckUI.Deck);
	}

	private void OnDragPanel(Vector2 dir)
	{
		if (dir.x >= 70f)
		{
			PrevPage();
		}
		else if (dir.x <= -70f)
		{
			NextPage();
		}
	}

	private void NextPage()
	{
		if (_pageList.Count > 1)
		{
			ChangePage(_currentPageIndex + 1, ChangeMoveDirection.RIGHT);
		}
	}

	private void PrevPage()
	{
		if (_pageList.Count > 1)
		{
			ChangePage(_currentPageIndex - 1, ChangeMoveDirection.LEFT);
		}
	}

	private void LoadResources(List<DeckData> deckDataList, Action onFinish)
	{
		if (_isInitialized)
		{
			DeleteResource();
		}
		_resourcePathList = new List<string>();
		List<int> list = new List<int>(deckDataList.Count);
		List<long> list2 = new List<long>(deckDataList.Count);
		foreach (DeckData deckData in deckDataList)
		{
			if (deckData.IsNoCard())
			{
				continue;
			}
			int skinId = deckData.GetSkinId();
			if (!list.Contains(skinId))
			{
				list.Add(skinId);
				_resourcePathList.Add(Toolbox.ResourcesManager.GetAssetTypePath(deckData.GetSkinId().ToString(), ResourcesManager.AssetLoadPathType.DeckListTexture));
			}
			long existingSleeveId = Toolbox.ResourcesManager.GetExistingSleeveId(deckData.GetDeckSleeveID());
			if (!list2.Contains(existingSleeveId))
			{
				list2.Add(existingSleeveId);
				_resourcePathList.Add(Toolbox.ResourcesManager.GetAssetTypePath(existingSleeveId.ToString(), ResourcesManager.AssetLoadPathType.SleeveTexture));
				Sleeve sleeve = Data.Master.SleeveMgr.Get(existingSleeveId);
				if (sleeve.IsPremiumSleeve)
				{
					UIManager.GetInstance().getUIBase_CardManager().AddPremireSleevePath(ref _resourcePathList, sleeve);
				}
			}
		}
		UIManager.GetInstance().createInSceneCenterLoading();
		UIManager.GetInstance().StartCoroutine(Toolbox.ResourcesManager.LoadAssetGroupAsync(_resourcePathList, delegate
		{
			UIManager.GetInstance().closeInSceneCenterLoading();
			onFinish.Call();
		}));
	}

	private void CreateDeckGroupPages(List<DeckGroup> deckGroupList, bool isVisibleCreateNew, Format format, DeckData primaryFirstDisplayDeck, IFirstDisplayPageIndexGetter firstDisplayPageIndexGetter)
	{
		_pageList = PageData.CreatePageList(deckGroupList, isVisibleCreateNew);
		bool flag = _pageList.Count > 0;
		_deckTableRoot.SetActive(flag);
		_noDeckText.gameObject.SetActive(!flag);
		_titleLabel.gameObject.SetActive(flag);
		_pageIndicatorOriginal.gameObject.SetActive(value: false);
		_pageIndicatorRoot.gameObject.SetActive(flag);
		if (flag)
		{
			if (_isInitialized && _pageIndicator != null)
			{
				UnityEngine.Object.Destroy(_pageIndicator.gameObject);
			}
			_pageIndicator = NGUITools.AddChild(_pageIndicatorRoot, _pageIndicatorOriginal.gameObject).GetComponent<UIPageIndicator>();
			_pageIndicator.gameObject.SetActive(value: true);
		}
		_flickCollider.gameObject.SetActive(flag);
		_rightButton.gameObject.SetActive(_pageList.Count > 1);
		_leftButton.gameObject.SetActive(_pageList.Count > 1);
		if (flag)
		{
			_currentPageIndex = firstDisplayPageIndexGetter.Get(_pageList, format, primaryFirstDisplayDeck, _canUseNonPossessionCard);
			_pageIndicator.Init(_pageList.Count, _currentPageIndex + 1);
			ChangePage(_currentPageIndex, ChangeMoveDirection.NONE);
		}
		else
		{
			OnChangePage.Call(format);
		}
	}

	private void ChangePage(int nextPageIndex, ChangeMoveDirection moveDirection)
	{
		if (!IsPageMoving && IsValidPageIndex(nextPageIndex))
		{
			PageData pageData = _pageList[nextPageIndex];
			_currentPageIndex = nextPageIndex;
			_titleLabel.text = pageData.GroupName;
			ChangeDeckTable(pageData, moveDirection);
			_pageIndicator.UpdateIndicator(_currentPageIndex + 1);
			_leftButton.gameObject.SetActive(0 < nextPageIndex);
			_rightButton.gameObject.SetActive(nextPageIndex < _pageList.Count - 1);
			OnChangePage.Call(pageData.Format);
		}
	}

	private bool IsValidPageIndex(int pageIndex)
	{
		if (_pageList.Count <= pageIndex)
		{
			return false;
		}
		if (pageIndex < 0)
		{
			return false;
		}
		return true;
	}

	private void ChangeDeckTable(PageData nextPageData, ChangeMoveDirection moveDirection)
	{
		if (IsPageMoving)
		{
			return;
		}
		DeckTable deckTable = _deckTables[_deckTableIndex];
		_deckTableIndex = 1 - _deckTableIndex;
		DeckTable deckTable2 = _deckTables[_deckTableIndex];
		deckTable2.UpdateDeckViewList(nextPageData.DeckViewList, _canUseNonPossessionCard);
		if (moveDirection == ChangeMoveDirection.NONE)
		{
			deckTable2.Obj.transform.localPosition = VIEW_PAGE_POSITION;
			deckTable.Obj.transform.localPosition = OUTSIDE_RIGHT_PAGE_POSITION;
			return;
		}
		bool flag = moveDirection == ChangeMoveDirection.RIGHT;
		deckTable.Obj.transform.localPosition = VIEW_PAGE_POSITION;
		deckTable2.Obj.transform.localPosition = (flag ? OUTSIDE_RIGHT_PAGE_POSITION : OUTSIDE_LEFT_PAGE_POSITION);
		IsPageMoving = true;
		TweenPosition.Begin(deckTable.Obj, 0.2f, flag ? OUTSIDE_LEFT_PAGE_POSITION : OUTSIDE_RIGHT_PAGE_POSITION);
		TweenPosition.Begin(deckTable2.Obj, 0.2f, VIEW_PAGE_POSITION).SetOnFinished(delegate
		{
			IsPageMoving = false;
		});
		GameMgr.GetIns().GetSoundMgr().PlaySe(Se.TYPE.SYS_SLIDE_BTN);
	}

	private void OnDestroy()
	{
		_isOnDestroy = true;
		DeleteResource();
	}

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

	public void SetPanelDepth(int depth)
	{
		_panel.depth = depth;
	}
}
