using System.Collections.Generic;
using System.Linq;

namespace Wizard.DeckSelect.FirstDisplayPageIndexGetter;

public class DefaultFirstDisplayPageIndexGetter : FirstDisplayPageIndexGetterBase
{
	protected override int DerivedGet(List<DeckSelectUI.PageData> pageList, Format viewFormat, bool canUseNonPossessionCard)
	{
		int lastSelectDeckId = 0;
		Format format = viewFormat;
		if (viewFormat == Format.Max || viewFormat == Format.All)
		{
			format = (Format)PlayerPrefsWrapper.GetValue(PlayerPrefsWrapper.LAST_SELECT_DECK_FORMAT);
		}
		switch (format)
		{
		case Format.Rotation:
			lastSelectDeckId = PlayerPrefsWrapper.GetValue(PlayerPrefsWrapper.LAST_SELECT_DECK_ID_ROTATION);
			break;
		case Format.Unlimited:
			lastSelectDeckId = PlayerPrefsWrapper.GetValue(PlayerPrefsWrapper.LAST_SELECT_DECK_ID_UNLIMITED);
			break;
		case Format.PreRotation:
			lastSelectDeckId = PlayerPrefsWrapper.GetValue(PlayerPrefsWrapper.LAST_SELECT_DECK_ID_PRE_ROTATION);
			break;
		case Format.Crossover:
			lastSelectDeckId = PlayerPrefsWrapper.GetValue(PlayerPrefsWrapper.LAST_SELECT_DECK_ID_CROSSOVER);
			break;
		case Format.MyRotation:
			lastSelectDeckId = PlayerPrefsWrapper.GetValue(PlayerPrefsWrapper.LAST_SELECT_DECK_ID_MY_ROTATION);
			break;
		case Format.Avatar:
			lastSelectDeckId = PlayerPrefsWrapper.GetValue(PlayerPrefsWrapper.LAST_SELECT_DECK_ID_AVATAR);
			break;
		case Format.Max:
			lastSelectDeckId = PlayerPrefsWrapper.GetValue(PlayerPrefsWrapper.LAST_BATTLE_DECK_ID);
			break;
		default:
			format = Format.Max;
			break;
		}
		for (int i = 0; i < pageList.Count; i++)
		{
			DeckSelectUI.PageData pageData = pageList[i];
			if (pageData.Format == format && pageData.DeckViewList.FirstOrDefault((DeckUI.DeckViewData deckView) => deckView.Deck.GetDeckID() == lastSelectDeckId) != null)
			{
				return i;
			}
		}
		if (TryGetPageIndexByAttribute(DeckAttributeType.CustomDeck, pageList, canUseNonPossessionCard, out var pageIndex))
		{
			return pageIndex;
		}
		if (TryGetPageIndexByAttribute(DeckAttributeType.TrialDeck, pageList, canUseNonPossessionCard, out pageIndex))
		{
			return pageIndex;
		}
		if (TryGetPageIndexByAttribute(DeckAttributeType.DefaultDeck, pageList, canUseNonPossessionCard, out pageIndex))
		{
			return pageIndex;
		}
		if (TryGetPageIndexByAttribute(DeckAttributeType.SampleDeck, pageList, canUseNonPossessionCard, out pageIndex))
		{
			return pageIndex;
		}
		return 0;
	}

	private static bool TryGetPageIndexByAttribute(DeckAttributeType attribute, List<DeckSelectUI.PageData> pageList, bool canUseNonPossessionCard, out int pageIndex)
	{
		for (int i = 0; i < pageList.Count; i++)
		{
			DeckSelectUI.PageData pageData = pageList[i];
			if (pageData.AttributeType == attribute && pageData.DeckViewList.FirstOrDefault((DeckUI.DeckViewData deckView) => deckView.Deck.IsUsable(canUseNonPossessionCard)) != null)
			{
				pageIndex = i;
				return true;
			}
		}
		pageIndex = 0;
		return false;
	}
}
