using UnityEngine;
using System.Collections;

public class ActionObject : MonoBehaviour {

	public GameController gameController;
	public Transform target;
	public Action actionType;
		
	public bool trigger4Coder = true;
	public bool trigger4Designer = true;
	public bool trigger4Sound = true;
	
	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
	
	}
	
	IEnumerator MyCoroutine(Collider other)
	{
		yield return new WaitForSeconds(1.0f);
		
		other.GetComponent<NavigationController>().target = target;
		other.GetComponent<NavigationController>().source = transform;
		
		if(actionType == Action.code) {
			gameController.increaseScore();
		} else if(actionType == Action.design) {
			gameController.increaseScore();
		} else if(actionType == Action.sound) {
			gameController.increaseScore();
		}
		NavigationController nc = other.GetComponent<NavigationController>();
		nc.GetRandomAction();
		other.GetComponent<NavMeshAgent>().Resume();
	}
	
	void OnTriggerEnter(Collider other) {
		
		Actor actor = other.GetComponent<NavigationController>().actor;
		if(actor == Actor.coder) {
			if(!trigger4Coder) return;
		} else if(actor == Actor.designer) {
			if(!trigger4Designer) return;
		} else if(actor == Actor.sound) {
			if(!trigger4Sound) return;
		}
		if(actor == Actor.coder) {
			trigger4Coder = false;
		} else if(actor == Actor.designer) {
			trigger4Designer = false;
		} else if(actor == Actor.sound) {
			trigger4Sound = false;
		}
	
		NavigationController nc = other.GetComponent<NavigationController>();
		
		if(nc.action == actionType) {
			other.GetComponent<NavMeshAgent>().Stop(true);
			Debug.Log(nc.transform);
			StartCoroutine(MyCoroutine(other));
		} else {
			other.GetComponent<NavigationController>().target = target;
			other.GetComponent<NavigationController>().source = transform;
		}
		RouteHandler rh = target.gameObject.GetComponent<RouteHandler>();
		CornerHandler ch = target.gameObject.GetComponent<CornerHandler>();
		
		if(rh != null) {
			if(actor == Actor.coder) {
				rh.trigger4Coder = true;
			} else if(actor == Actor.designer) {
				rh.trigger4Designer = true;
			} else if(actor == Actor.sound) {
				rh.trigger4Sound = true;
			} 
		} else if(ch != null) {
			if(actor == Actor.coder) {
				ch.trigger4Coder = true;
			} else if(actor == Actor.designer) {
				ch.trigger4Designer = true;
			} else if(actor == Actor.sound) {
				ch.trigger4Sound = true;
			} 
		} 
		
		if(nc.action != actionType) {
			gameController.LoseLife();
		}
	}
}
