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

namespace Wizard.DeckSelect.FirstDisplayPageIndexGetter;

public class QuestFirstDisplayPageIndexGetter : FirstDisplayPageIndexGetterBase
{
	protected override int DerivedGet(List<DeckSelectUI.PageData> pageList, Format viewFormat, bool canUseNonPossessionCard)
	{
		int questStageId = GameMgr.GetIns().GetDataMgr().QuestBattleData.QuestStageId;
		QuestLastUsedDeckSaveDataManager.ExtractedDeckData deck = new QuestLastUsedDeckSaveDataManager().GetDeck(questStageId);
		if (deck == null || !TryGetPageIndex(pageList, deck, out var pageIndex))
		{
			return new DefaultFirstDisplayPageIndexGetter().Get(pageList, viewFormat, null, canUseNonPossessionCard);
		}
		return pageIndex;
	}

	private static bool TryGetPageIndex(List<DeckSelectUI.PageData> pageList, QuestLastUsedDeckSaveDataManager.ExtractedDeckData deckData, out int pageIndex)
	{
		for (int i = 0; i < pageList.Count; i++)
		{
			DeckSelectUI.PageData pageData = pageList[i];
			if (pageData.Format == deckData.Format && pageData.DeckViewList.Any((DeckUI.DeckViewData x) => x.Deck.GetDeckID() == deckData.ID))
			{
				pageIndex = i;
				return true;
			}
		}
		pageIndex = 0;
		return false;
	}
}
