using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using Utils;

namespace Game
{
	[CreateAssetMenu(menuName = "Game Screens/Room Screen")]
	public class RoomScreenAsset : GameScreenAsset
	{
		[SerializeField] private VisitedScreensManager visitedScreensManager;
		[SerializeField] private List<TextChoice> randomOptions;
		[SerializeField] private TextChoice backToCorridorOption;

		private List<TextChoice> availableChoices;

		public override List<TextChoice> Choices
		{
			get { return availableChoices; }
		}

		public override bool UseTextChoice
		{
			get { return true; }
		}

		public override bool HideNextScreenInspector
		{
			get { return true; }
		}

		public override void Enter()
		{
			base.Enter();
			
			if (VisitsCount == 0)
			{
				availableChoices = new List<TextChoice>();
				availableChoices.AddRange(choices);
				
				randomOptions.Shuffle();
				int freeChoiceSlots = 4 - availableChoices.Count;
				for (int i = 0; i < freeChoiceSlots; i++)
				{
					var randomOption = randomOptions.FirstOrDefault(o => !availableChoices.Contains(o) && !visitedScreensManager.WasVisited(o.nextScreen));
					if (randomOption == null)
						break;
					
					availableChoices.Add(randomOption);
				}
				
				foreach (var choice in availableChoices)
				{
					choice.Selected += RemoveChoice;
				}
				
				availableChoices.Shuffle();
			}
			else if (VisitsCount > 0 && !availableChoices.Contains(backToCorridorOption))
			{
				availableChoices.Add(backToCorridorOption);
			}
		}

		private void RemoveChoice(TextChoice choice)
		{
			if (availableChoices.Contains(choice))
				availableChoices.Remove(choice);
		}
	}
}