using UnityEngine;
using System.Collections;

public class TruckControls : MonoBehaviour {

	float speed = 0.1f;
	float turnrate = 0.01f;

	GameObject body;
	GameObject wheelBL;
	GameObject wheelBR;
	GameObject wheelFL;
	GameObject wheelFR;

	Rigidbody rbBody;
	Rigidbody rbBL;
	Rigidbody rbBR;
	Rigidbody rbFL;
	Rigidbody rbFR;

	bool alive;
	
	// Use this for initialization
	void Start () 
	{
		alive = true;

		if (null != GameObject.Find("Halp"))
		{
			alive = false;
		}

		body = transform.Find("body_default").gameObject;
		wheelBL = transform.Find("wheelBL_default").gameObject;
		wheelBR = transform.Find("wheelBR_default").gameObject;
		wheelFL = transform.Find("wheelFL_default").gameObject;
		wheelFR = transform.Find("wheelFR_default").gameObject;

		rbBL = wheelBL.GetComponent<Rigidbody>();
		rbBR = wheelBR.GetComponent<Rigidbody>();
		rbFL = wheelFL.GetComponent<Rigidbody>();
		rbFR = wheelFR.GetComponent<Rigidbody>();

		rbBody = body.GetComponent<Rigidbody>();
	}
	
	// Update is called once per frame
	void FixedUpdate () 
	{
		if (!alive)
			return;

		float forwards = Input.GetAxis("Vertical") * speed;
		float leftright = Input.GetAxis("Horizontal") * turnrate;

		float fl = forwards;
		float fr = forwards;
		float bl = forwards;
		float br = forwards;

		//wheelFL.transform.eulerAngles = new Vector3(0,leftright,0);
		//wheelFR.transform.eulerAngles = new Vector3(0,leftright,0);

		/*
		rbBL.angularVelocity = bl * wheelBL.transform.right;
		rbBR.angularVelocity = br * wheelBL.transform.right;
		rbFL.angularVelocity = fl * wheelBL.transform.right;
		rbFR.angularVelocity = fr * wheelBL.transform.right;
		*/

		//rbBody.AddForce(forwards * 0.4f * body.transform.forward);

		//rbBody.AddForceAtPosition(forwards * 1.2f * body.transform.forward, 
		//                          body.transform.position);// + (0.1f*body.transform.forward) - (0.35f*body.transform.up));

		//rbBody.AddForceAtPosition (forwards * 0.6f * body.transform.forward, body.transform.position + (0.05f*Vector3.down));

		rbBody.AddForceAtPosition (forwards * 0.6f * body.transform.forward, body.transform.position + (0.03f*Vector3.down));


		rbFL.AddForce(leftright * body.transform.forward);
		rbFR.AddForce(-leftright * body.transform.forward);
		rbBL.AddForce(leftright * body.transform.forward);
		rbBR.AddForce(-leftright * body.transform.forward);

		//wheelFL.transform.localPosition = new Vector3(0.05f,0,leftright);
		//wheelFR.transform.localPosition = new Vector3(0.05f,0,-leftright);

		rbBL.AddRelativeTorque(bl * Vector3.right);
		rbBR.AddRelativeTorque(br * Vector3.right);
		rbFL.AddRelativeTorque(fl * Vector3.right);
		rbFR.AddRelativeTorque(fr * Vector3.right);

	}
}
