using UnityEngine;
using System.Collections;

public class Target : MonoBehaviour {
	
	public int Colour;
	public GameObject trailer;

	public void SetTrailer(GameObject tr)
	{
		trailer = tr;
		SetColour(trailer.GetComponent<Trailer>().Colour);
	}

	public void SetColour(int c)
	{
		Colour = c;
		Material colourMaterial;
		
		if (Colour == 0)
		{
			colourMaterial = Resources.Load("CustomMaterials/Trailer1", typeof(Material)) as Material;
		}
		else if (Colour == 1)
		{
			colourMaterial = Resources.Load("CustomMaterials/Trailer2", typeof(Material)) as Material;
		}
		else
		{
			colourMaterial = Resources.Load("CustomMaterials/Trailer3", typeof(Material)) as Material;
		}
		
		Debug.Log (colourMaterial.name);
		
		transform.Find ("body").gameObject.GetComponent<Renderer>().material = colourMaterial;
	}

	public bool Pass()
	{
		if (null == trailer)
			return false;
		return (Mathf.Abs(trailer.transform.Find("body").GetComponent<Rigidbody>().position.x - transform.position.x) + Mathf.Abs(trailer.transform.Find("body").GetComponent<Rigidbody>().position.z - transform.position.z) < 3);
	}

	// Use this for initialization
	void Start () {
		//SetColour(Random.Range(0,3));
	}
	
	// Update is called once per frame
	void FixedUpdate () {
		if (null == trailer)
			return;



		if (Pass ())
		{
			Rigidbody trailerBody = trailer.transform.Find("body").GetComponent<Rigidbody>();
			trailerBody.AddForce(-0.000005f*trailerBody.velocity);
			transform.Find ("centre").gameObject.GetComponent<Renderer>().material = transform.Find ("body").gameObject.GetComponent<Renderer>().material;
		}
		else
		{
			transform.Find ("centre").gameObject.GetComponent<Renderer>().material = (Material)(Resources.Load("CustomMaterials/White"));
		}
	}
}
