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

/// <summary>
/// Visually represents an agent as a selectable button.
/// </summary>
public class AgentWidget : BaseBehaviour
{
	[SerializeField, Tooltip("The color used for each agent recruited in order")]
	private Color[] colorList;
	[SerializeField]
	private Image portraitImage;
	[SerializeField]
	private Image highlightImage;
	[SerializeField]
	private Text nameLabel;
	[SerializeField]
	private GameObject awayIndicator;

	private Selectable thisSelectable;
	
	private int index;
	private int portrait;

	private AgentGenerator agentGen;
	private ViewAgentsPanel viewAgentsPanel;
	private DosierPanel dosierPanel;

	private Agent agentInfo;

	/// <summary>
	/// The agent info held in this widget.
	/// </summary>
	public Agent AgentInfo { get { return agentInfo; } }

	protected virtual void Awake()
	{
		Init();
	}

	private void Init()
	{
		if (agentGen != null) return;

		if (colorList.Length == 0)
			LogError("No colors set");

		ReferenceManager.GetBehaviours(ref agentGen, ref viewAgentsPanel, ref dosierPanel);

		CheckIfSet(portraitImage, highlightImage, nameLabel);
		CheckIfSet(awayIndicator);

		GetComponentsWithNullCheck(ref thisSelectable);

		if (awayIndicator != null)
			awayIndicator.SetActive(false);
	}

	public void Init(Agent agentInfo, int index)
	{
		Init();

		this.index = index;
		this.agentInfo = agentInfo;

		if(colorList != null && colorList.Length > 0 && highlightImage != null)
		{
			var newColor = colorList[index % colorList.Length];
			highlightImage.color = newColor;
		}

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

		if (nameLabel != null)
			nameLabel.text = agentInfo.Name;

		if (thisSelectable != null)
			thisSelectable.interactable = !agentInfo.Away;

		if (awayIndicator != null)
			awayIndicator.SetActive(agentInfo.Away);
	}

	public void OnClick()
	{
		viewAgentsPanel.Hide();
		dosierPanel.Show(agentInfo);
	}
}
