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

public class Crew : MonoBehaviour
{
	private BaseRoom homeRoom;
	private Job job;

	public List<Transform> pathNodes;

	public float speed = 5f;
	public string Name;
	public int Health;

	bool havePath = false;

	private GameController gameController;
	private JobController jobController;
	private CapsuleCollider capCollider;
	private RoomJobPair roomJobPair;
	private bool IsMoiving = false;

	void Awake ()
	{
		var gameControllerGO = GameObject.FindGameObjectWithTag ("GameController");
		if (gameControllerGO != null)
			gameController = gameControllerGO.GetComponent<GameController> ();
		
		capCollider = GetComponent<CapsuleCollider> ();
	}

	public void MoveToRoom ()
	{
		pathNodes.Clear ();
		//pathNodes.AddRange (gameController.DetectRoom (transform.position) [gameController.GetRoom ().name]);
		havePath = true;
	}

	public void MoveToRoom (BaseRoom room)
	{
		if (room != null) {
			pathNodes.Clear ();

			pathNodes.AddRange (gameController.DetectRoom (transform.position) [room.name]);
			havePath = true;
		}
	}

	void OnMouseDown ()
	{
		Debug.Log ("Clicked on " + gameObject.name + " crewmember.");
		if (!havePath) {
			if (Input.GetMouseButtonDown (0)) {
				gameController.SelectedCrew = this;
			}
		}
	}

	public void Update ()
	{
//		if (Input.GetMouseButtonDown (0)) {
//			Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
//			RaycastHit hit;
//
//			if (Physics.Raycast (ray, out hit)) {
//				gameController.SelectedCrew = this;
//			}
//		}

		if (pathNodes.Count > 0) {
			transform.position = Vector3.MoveTowards (transform.position, pathNodes [0].position, speed * Time.deltaTime);

			if (transform.position == pathNodes.FirstOrDefault ().transform.position) {
				// Dump that node like it's hawt.
				pathNodes.RemoveAt (0);
			}
		} else {
			havePath = false;
		}
		//else {
//			StartCoroutine (job.DoWork ());
//
//			if (job.transform.position != transform.position) {
//				havePath = true;
//				MoveToRoom (homeRoom);
//			}
//		}
	}

	public void AssignJob (Job newJob)
	{
		//GetComponent<

//		job = newJob;
//		homeRoom = gameController.GetRoomByJob (job);
//
//		if (job.GetWorkingRoom () == null) {
//			job.SetWorkingRoom(homeRoom);
//		}
//		MoveToRoom (job.GetWorkingRoom());
	}

	public void RemoveJob ()
	{
		job.StopWork ();
		homeRoom = null;
		job = null;
	}
}
