using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MissionDisplayPanel : PanelBase
{
	[SerializeField]
	private WidgetList missionWidgetList;

	[SerializeField]
	private Transform locationList;

	private AgentManager agentManager;
	private MissionManager missionManager;

	private List<MissionWidget> missionList;
	private List<MissionWidget> missionsInProgress;


	protected override void Awake()
	{
		base.Awake();

		ReferenceManager.GetBehaviours(ref agentManager, ref missionManager);

		CheckIfSet(missionWidgetList, locationList);

		missionList = new List<MissionWidget>();
		missionsInProgress = new List<MissionWidget>();
	}

	public void AddMission(Mission missionInfo)
	{
		missionInfo.Location = GetRandomLocation();
		var newWidget = missionWidgetList.AddWidget<MissionWidget>();
		newWidget.Init(missionInfo);
		missionList.Add(newWidget);
	}

	public void RemoveMission(Mission missionInfo)
	{
		int missionIndex = missionList.FindIndex(x => x.MissionInfo == missionInfo);
		if (missionIndex == -1) return;
		missionList.RemoveAt(missionIndex);
		missionWidgetList.RemoveAt(missionIndex);
	}

	public void StartMission(Mission missionInfo, Agent[] agentList)
	{
		if(missionsInProgress.Find(x => x.MissionInfo == missionInfo) != null)
		{
			LogError("Mission has already started");
			return;
		}

		StartCoroutine(_StartMission(missionInfo, agentList));
	}

	private void SetMissionToInProgress(Mission missionInfo)
	{
		int missionIndex = missionList.FindIndex(x => x.MissionInfo == missionInfo);
		if (missionIndex == -1)
		{
			LogError("Couldn't find mission");
			return;
		}

		missionsInProgress.Add(missionList[missionIndex]);
		missionList[missionIndex].DisableMission();
    }

	private void RemoveMissionFromInProgress(Mission missionInfo)
	{
		int missionIndex = missionsInProgress.FindIndex(x => x.MissionInfo == missionInfo);
		if (missionIndex == -1)
		{
			LogError("Couldn't find mission");
			return;
		}

		missionsInProgress.RemoveAt(missionIndex);
	}

	private IEnumerator _StartMission(Mission missionInfo, Agent[] agentList)
	{
		int missionIndex = missionList.FindIndex(x => x.MissionInfo == missionInfo);

		// disable agents
		for (int i = 0; i < agentList.Length; i++)
			agentManager.SetAgentToAway(agentList[i], missionInfo.Duration);

		// disable mission
		SetMissionToInProgress(missionInfo);


		// wait
		yield return new WaitForSeconds(missionInfo.Duration);
		// TODO show progress bars

		// remove mission
		RemoveMissionFromInProgress(missionInfo);
		
		missionManager.CompleteMission(missionInfo, agentList);
	}

	private Vector2 GetRandomLocation()
	{
		if (locationList == null) return Vector2.zero;

		var childIndex = Random.Range(0, locationList.childCount);
		var childTransform = locationList.GetChild(childIndex);

		return childTransform.localPosition;
	}
}
