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

public class ViewAgentsPanel : PanelBase
{

	[SerializeField]
	private WidgetList agentWidgetList;
	[SerializeField]
	private Text minMaxAgentsLabel;
	[SerializeField]
	private Button recruitButton;
	[SerializeField]
	private int recruitAgentCost = 10;

	private AgentManager agentManager;
	private GameManager gameManager;

	private List<Agent> lastAgentList;

	private bool CanRecruit
	{
		get
		{
			bool canRecruit = gameManager.InfluencePoints >= recruitAgentCost;
			if (canRecruit)
			{
				if (agentManager.AgentsAtMaxLimit)
					canRecruit = false;
			}
			return canRecruit;
		}
	}

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

		CheckIfSet(agentWidgetList, recruitButton, minMaxAgentsLabel);

		ReferenceManager.GetBehaviours(ref agentManager, ref gameManager);

		gameEvents.Subscribe(GAME_EVENT.AgentAwayStatusChanged, this);
		gameEvents.Subscribe(GAME_EVENT.InfluencePointsChanged, this);
		gameEvents.Subscribe(GAME_EVENT.AgentCountChanged, this);
		gameEvents.Subscribe(GAME_EVENT.ProgressionLevelChanged, this);

		if (recruitButton != null)
			recruitButton.interactable = false;
	}

	public override void OnGameEvent(GAME_EVENT eventType, object args)
	{
		base.OnGameEvent(eventType, args);

		switch(eventType)
		{
			case GAME_EVENT.AgentAwayStatusChanged:
				Refresh();
				break;
			case GAME_EVENT.InfluencePointsChanged:
				UpdateRecruitButton();
				break;
			case GAME_EVENT.AgentCountChanged:
				UpdateMinMaxLabel();
				break;
			case GAME_EVENT.ProgressionLevelChanged:
				UpdateMinMaxLabel();
				break;
		}
	}

	public void DisplayAgents(List<Agent> agentList)
	{
		this.lastAgentList = agentList;
        agentWidgetList.ClearList();

		for (int i = 0; i < agentList.Count; i++)
			AddAgent(agentList[i], i);
	}

	public void Refresh()
	{
		if (lastAgentList != null)
			DisplayAgents(lastAgentList);
	}

	public void OnRecruitAgent()
	{
		if (!CanRecruit) return;

		agentManager.RecruitAgent();
		gameManager.RemoveInfluencePoints(recruitAgentCost);
	}

	private void AddAgent(Agent agent, int index)
	{
		var newWidget = agentWidgetList.AddWidget<AgentWidget>();
		newWidget.Init(agent, index);
	}

	private void UpdateRecruitButton()
	{
		recruitButton.interactable = CanRecruit;
    }

	private void UpdateMinMaxLabel()
	{
		minMaxAgentsLabel.text = string.Format("{0} / {1}", agentManager.AgentList.Count, agentManager.MaxAgents);
	}

}
