﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour {

	public GameManager playerManager;
	public GameObject BottomBody;
	public GameObject UpperBody;
	public GameObject RightHand;
	public GameObject LeftHand;
	public Camera mainCamera;
	public GameObject cameraTarget;
	public float moveSpeed;
	public float moveRotateSpeed;
	public float rotateSpeed;

	public GameObject[] AxisDummies;

	public GunController theGun;

	private Rigidbody myRigidbody;
	private Animator myAnimator;

	private Vector3 moveInput;
	private Vector3 moveVelocity;


	void Start () {

		myRigidbody = GetComponent<Rigidbody>();
		myAnimator = GetComponent<Animator>();

		playerManager = FindObjectOfType <GameManager>();
	}

	void Update () {

		if (playerManager.gamePaused == false & playerManager.playerFreezed == false){


		cameraTarget.transform.position = gameObject.transform.position;

		Ray cameraRay = mainCamera.ScreenPointToRay(Input.mousePosition);
		Plane groundPlane = new Plane(Vector3.up, Vector3.zero);
		float rayLength;

		if (groundPlane.Raycast(cameraRay, out rayLength))
		{
			Vector3 pointToLook = cameraRay.GetPoint(rayLength);
			Debug.DrawLine(cameraRay.origin, pointToLook, Color.red);


			Quaternion UpperBodyRotation = Quaternion.LookRotation (pointToLook - transform.position);
			Quaternion RightHandRotation = Quaternion.LookRotation (pointToLook - RightHand.transform.position);
			Quaternion LeftHandRotation = Quaternion.LookRotation (pointToLook - LeftHand.transform.position);

			UpperBody.transform.rotation = Quaternion.Slerp (UpperBody.transform.rotation, UpperBodyRotation, rotateSpeed * Time.deltaTime);
			RightHand.transform.rotation = Quaternion.Slerp (RightHand.transform.rotation, RightHandRotation, rotateSpeed * 0.25f * Time.deltaTime);
			LeftHand.transform.rotation = Quaternion.Slerp (LeftHand.transform.rotation, LeftHandRotation, rotateSpeed * 0.25f * Time.deltaTime);

		}


	if (Input.GetMouseButtonDown(0))
	theGun.isFiring = true;

	if (Input.GetMouseButtonUp(0))
	theGun.isFiring = false;

	}
	}


	void FixedUpdate () {

		if (playerManager.playerAntiMove == false){


		float horizontal = Input.GetAxis("Horizontal");
		float vertical = Input.GetAxis("Vertical");

		myAnimator.SetFloat("Vert", vertical);
		myAnimator.SetFloat("Horiz", horizontal);

		Vector3 move = new Vector3 (horizontal, 0 ,vertical);

		if ((horizontal - vertical) == 0f | (horizontal - vertical) == 2f | (horizontal - vertical) == -2f){

			move = move / 1.5f;
		}

		myRigidbody.AddForce (move * moveSpeed / Time.deltaTime);

/*
		if (Input.GetAxis("Vertical") != 0 | Input.GetAxis("Horizontal") != 0)
		{
			myAnimator.enabled = true;
		}
		else { myAnimator.enabled = false;}
*/
		}
	}

}
