// Benjamin Gordon, 2016

using UnityEngine;

public class ShrapnelGamePlayerMover : FirstPersonCamMover {

    [Header("SoundStuff")]
    public float walkingNoise = 8;
    public float shootingNoise = 25;
    public float attackDeerNoise = 15;
    public SphereCollider noiseSphere;
    public GunShotManager gunShot;
    public bool shooting;
    public AudioSource footStepSource;
    public AudioClip[] footsteps;
    public float footstepDelay;
    protected float footstepTimer;

    [Header("Ragdoll")]
    [SerializeField] float stopRagdollForce = 0.3f;
    bool ragdolled = false;
    int frameHack = 30;

    protected override void FixedUpdate() {
        RetrieveInput();

        // Rotate (all the time)
        Rotate();

        //Debug.Log("On Ground: " + onGround);

        // Allow for ragdolling to affect movement.
        if(!RagDolled) {
            //Debug.Log("Not Ragdolled!");
            PerformMovement();
            Jump();
        }

        if(rigidBody.velocity.magnitude < stopRagdollForce && frameHack <= 0) {
            RagDolled = false;
            frameHack = 30;
        }else {
            frameHack--;
        }

        //if(!onGround)
        AddGravity(); // Always add gravity force to object.

        // A check that allows the logic for jumping to function.
        onGround = false;
    }

    protected override void PerformMovement()
    {
        if (Mathf.Abs(V) > gamepadError || Mathf.Abs(H) > gamepadError)
        {
            Movement();
            noiseSphere.radius = walkingNoise;
            CreateFootstepSound();
        }
        else {
            if(!shooting)
                noiseSphere.radius = 1;

            if (HeadAnimator.GetFloat(speedParam) != 0)
                HeadAnimator.SetFloat(speedParam, 0); 
        }  
    }

    public void Shoot() {
        gunShot.Shoot();
    }

    public void Attack() {
        noiseSphere.radius = attackDeerNoise;
    }

    public bool RagDolled {
        set {
            ragdolled = value;
            //Debug.Log("RB Velocity Magnitude: " + rigidBody.velocity.x);
            if(ragdolled) {
                //col.material = ragdollMat;
                //Debug.Log("We are being ragdolled!");
            }
        }
        get { return ragdolled; }
    }

    protected void CreateFootstepSound()
    {
        if (Time.time > footstepTimer)
        {
            footstepTimer = Time.time + footstepDelay;
            footStepSource.PlayOneShot(footsteps[Random.Range(0, footsteps.Length)]);
        }
    }
}
