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

public class Player : PlayerController
{
	public PlayerInventory inventory;
	public List<ComfortZone> currectComfortStates = new List<ComfortZone>();

    public delegate void ClickAction(GameObject gO);
    public static event ClickAction LocatedNearAnItem;

    protected string lastCallbackTarget;

    void Awake()
	{
		//GameManager.instance.player = this;
	}

	public override void Start()
	{
		base.Start();
		GameManager.instance.player = this;
	}

	public override void Update()
	{

		if (Input.GetMouseButton(0))
		{
			if (!EventSystem.current.IsPointerOverGameObject())
			{
				base.Update();
			}
		}
		if(currectComfortStates.Count > 0)
		{
			ApplyComfortModifiers();
		}
        if (hitGameObject != null && hitGameObject.tag == "Item")
        {
            if (hitGameObject.transform.position.x - transform.position.x < 1 && hitGameObject.transform.position.z - transform.position.z < 1)
			{
				if (LocatedNearAnItem != null && lastCallbackTarget != hitGameObject.name)
				{
					LocatedNearAnItem(hitGameObject);
                    lastCallbackTarget = hitGameObject.name;
				}
			} else
            {
                lastCallbackTarget = "";
            }
        }
    }

	/// <summary>
	/// Add or remove ComfortState to player
	/// </summary>
	/// <param name="zone">Which zone to process</param>
	/// <param name="add">Add or remove it from state list</param>
	public void SetComfortState(ComfortZone zone, bool add)
	{
		bool isIt = false;
		for (int i = 0; i < currectComfortStates.Count; i++)
		{
			var state = currectComfortStates[i];
			if (state == zone && !add)
			{
				currectComfortStates.RemoveAt(i);
				break;
			}
			if(state == zone && add)
			{
				isIt = true;
			}
			
		}
		if(add && !isIt)
		{
			currectComfortStates.Add(zone);
		}
	}

	void ApplyComfortModifiers()
	{
		float modifier = currectComfortStates.Sum(states => GameManager.instance.GetModifierAmount(states));
		GlobalTime.comfortModifier = modifier;
	}
}
