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

/// <summary>
/// Holds backstory and current events about the agent
/// </summary>
public class DosierPanel : PanelBase
{
	
	[SerializeField]
	private Text titleLabel;
	[SerializeField]
	private WidgetList historyWidgetList;
	[SerializeField]
	private Button accuseButton;
	[SerializeField]
	private Image agentPortrait;
	[SerializeField]
	private int requiredEvidence = 3;
	[SerializeField]
	private int accuseCost = 10;

	private AgentGenerator agentGen;
	private GameManager gameManager;
	private AgentManager agentManager;
	private ViewAgentsPanel viewAgentsPanel;

	private Agent currentAgent;
	private List<HistoryWidget> evidenceList;

	private bool CanAccuse
	{
		get
		{
			return evidenceList.Count >= requiredEvidence && gameManager.InfluencePoints >= accuseCost;
        }
	}

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

		ReferenceManager.GetBehaviours(ref agentGen, ref viewAgentsPanel, ref agentManager);
		ReferenceManager.GetBehaviours(ref gameManager);

		CheckIfSet(historyWidgetList, accuseButton, agentPortrait);

		evidenceList = new List<HistoryWidget>();

		accuseButton.interactable = false;
    }

	public void Show(Agent agentInfo)
	{
		base.Show();

		this.currentAgent = agentInfo;

		evidenceList.Clear();
		accuseButton.interactable = false;

		titleLabel.text = agentInfo.Name;

		if (agentInfo.Gender == Gender.Male)
			agentPortrait.sprite = agentGen.MalePortraitList[agentInfo.PortraitIndex];
		else if (agentInfo.Gender == Gender.Female)
			agentPortrait.sprite = agentGen.FemalePortraitList[agentInfo.PortraitIndex];

		// add backstory
		historyWidgetList.ClearList();
		foreach (var backstory in agentInfo.BackstoryList)
		{
			var newWidget = historyWidgetList.AddWidget<HistoryWidget>();
			newWidget.Init(backstory);
		}

		// TODO add agent recent history
	}

	public void OnHistorySelected(HistoryWidget widget)
	{
		// if evidence is full, auto deselect
		if(evidenceList.Count >= requiredEvidence)
		{
			widget.AutoDeselect();
			return;
		}

		if (!evidenceList.Contains(widget))
			evidenceList.Add(widget);

		accuseButton.interactable = CanAccuse;
    }

	public void OnHistoryDeselected(HistoryWidget widget)
	{
		evidenceList.Remove(widget);

		accuseButton.interactable = CanAccuse;
	}

	public void OnBack()
	{
		viewAgentsPanel.Show();
		Hide();
	}

	public void OnAccuse()
	{
		if (!CanAccuse) return;

		gameManager.RemoveInfluencePoints(accuseCost);
		agentManager.RemoveAgent(currentAgent, evidenceList);

		OnBack();
	}

}
