using UnityEngine;
using System.Collections;

public class TankController : MonoBehaviour {

    public float speed = 6.0f;
    public float turnSpeed = 90;
    public float strafeSpeed = 3.0f;

    public GameObject turretGameobject;
    public Transform canonTracer;
    public float turretTurnSpeed = 45;

    public Transform groundCheck;

    private Rigidbody playerRigidbody;

    public float rayDistance = 200;

    private float movement;
    private float rotation;

    void Start()
    {
        playerRigidbody = gameObject.GetComponent<Rigidbody>();
    }

    // Update is called once per frame
	void FixedUpdate ()
    {
        if(gameObject.tag == "Player")
        {
            //Debug.Log("FORWARD = " + Input.GetAxis("Vertical") + " / STRAFE = " + Input.GetButtonDown("StrafeLeft") + " " + Input.GetButtonDown("StrafeRight") + " / TURN = " + Input.GetAxis("Vertical"));
            //Tank movement and rotation

            Vector3 fwd = transform.TransformDirection(Vector3.up);

            Debug.DrawRay(groundCheck.position, -transform.forward, Color.green);

            if (Physics.Raycast(groundCheck.position, -transform.forward, 20f))
            {
                movement = Input.GetAxis("Vertical") * speed;
                rotation = Input.GetAxis("Turn") * turnSpeed;
                //print("controls are on");
            }
            else
            {
                print("did we fall off something?");
            }
            playerRigidbody.AddRelativeForce(-movement * speed, 0, 0);


            playerRigidbody.AddRelativeTorque(0, 0, rotation * turnSpeed);
            Debug.DrawRay(transform.position, -fwd * 0.8f, Color.red);






            turretGameobject.transform.Rotate(0, Input.GetAxis("TurretRotation") * turretTurnSpeed * Time.deltaTime, 0);

            if (Input.GetButtonDown("ResetTurret"))
            {
                iTween.RotateTo(turretGameobject, iTween.Hash("y", 0, "islocal", true, "time", 1.0f, "easetype", iTween.EaseType.linear));
            }

            //Strafe impulses
            if (Input.GetButtonDown("StrafeLeft"))
            {
                iTween.MoveBy(gameObject, iTween.Hash("x", -2f, "islocal", true, "easetype", iTween.EaseType.easeInOutSine, "time", 0.25f));
            }
            else if (Input.GetButtonDown("StrafeRight"))
            {
                iTween.MoveBy(gameObject, iTween.Hash("x", 2f, "islocal", true, "easetype", iTween.EaseType.easeInOutSine, "time", 0.25f));
            }

            //Canon
            if (Input.GetButtonDown("Fire1"))
            {
                Debug.DrawRay(canonTracer.position, canonTracer.forward * rayDistance, Color.red, 1.0f);
            }
        }        
    }
}
