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

public class PlayerController : MonoBehaviour
{

    protected Animator treeAnimator;

    protected bool targetSetAnimal;
    protected bool targetSetTree;

    protected string defaultTag;

    protected RaycastHit hitFinal;
    protected Vector3 destination;
    protected NavMeshAgent agent;
	protected GameObject hitGameObject;

	public virtual void Start()
	{
		agent = GetComponent<NavMeshAgent>();
		destination = agent.destination;
	}

	void movePosition()
	{
		Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
		if (Physics.Raycast(ray, out hitFinal, 100))
		{
			movePositionAndChecks();
		}
	}

	void movePositionAndChecks()
	{
		destination = new Vector3(hitFinal.point.x, 0, hitFinal.point.z);

        defaultTag = hitFinal.transform.tag;
        if (Vector3.Distance(destination, transform.position) > 1)
		{
			if (defaultTag == "Terrain" || defaultTag == "Item")
			{
				agent.destination = destination;
				targetSetAnimal = false;
			}
		}
		hitGameObject = hitFinal.transform.gameObject;
	}

	public virtual void Update()
	{
		if(Input.GetMouseButtonDown(0) && defaultTag == "Sheep" || defaultTag == "Chicken")
		{
			targetSetAnimal = true;
		}

		if(Input.GetMouseButtonDown(0) && defaultTag == "Tree")
		{
			targetSetTree = true;
		}

		if (targetSetTree == true)
		{
			TreeMining();
		}

		if (targetSetAnimal == true)
		{
			FollowingAnimal();
		}

		if (Input.GetMouseButtonDown(0))
		{
			movePosition();
		}
	}

	void TreeMining()
	{
		if (hitGameObject != null)
		{
			if (destination.x - transform.position.x < 1f && destination.z - transform.position.z < 1f)
			{ 
				treeAnimator = hitGameObject.GetComponent<Animator>();

				StartCoroutine("ChoppingTree");
				targetSetTree = false;
			}
		}
	}

	void FollowingAnimal()
	{ 
		destination = new Vector3(hitGameObject.transform.position.x, 0, hitGameObject.transform.position.z);
	
		if (Vector3.Distance(destination, transform.position) > 1)
		{
			agent.destination = destination;
		}
	}

	IEnumerator ChoppingTree()
	{
		if (treeAnimator != null)
		{
			Debug.Log("I get here");

			treeAnimator.SetTrigger("ChopTree");
			yield return new WaitForSeconds(3f);
			treeAnimator.SetTrigger("FellTree");
			yield return new WaitForSeconds(3f);
			hitGameObject.GetComponent<BoxCollider>().enabled = false;
			hitGameObject.GetComponentInChildren<NavMeshObstacle>().enabled = false;
			hitGameObject.transform.Find("TheTree").gameObject.SetActive(false);
		}
	}
}
