using System.Collections;
using UnityEngine;
//using System.Collections;

[RequireComponent(typeof(AudioSource))]
public class PlayerGunManager : MonoBehaviour {

    [Header("Stats")]
    [SerializeField] private int gunDamage = 30;

    [Header("Setup")]
    public Transform gunTip;
	public Camera playerCamera;
    public LineRenderer gunLazor;
    public GameObject lazorParticle;
    public float lazorDuration;
    public float aimFOV = 30;
    public float fovChangeSpeed = 3;
    public ShrapnelGamePlayerMover mover;

    public AudioClip[] lazorSounds;

    private float lazorTimer;
    //private bool firing = false;
    
    private AnimatorStateInfo headLayer1StateInfo;
    private AnimatorStateInfo headLayer0StateInfo;
    public Animator headAnimator;
    public Animator gunAnimator;
    private int fireTriggerHash;
    private int aimBoolHash;
    private int fireWeaponStateHash;
    private int weaponIdleStateHash;

    private float defaultFOV;

    private AudioSource source;

    void Start() {
        if(headAnimator == null) {
            Debug.LogError("Hey, you dont have an animator on this player's head, or you dont have a head attached!");
             return;
        }

        defaultFOV = playerCamera.fieldOfView;

        source = GetComponent<AudioSource>();

        headLayer1StateInfo = headAnimator.GetCurrentAnimatorStateInfo(1);
        headLayer0StateInfo = headAnimator.GetCurrentAnimatorStateInfo(0);

        fireTriggerHash = Animator.StringToHash("FireWeaponTrigger");
        aimBoolHash = Animator.StringToHash("AimedBool");
        fireWeaponStateHash = Animator.StringToHash("FireWeapon2");
        weaponIdleStateHash = Animator.StringToHash("HeadBob");

        gunLazor.enabled = false;
    }

	// Update is called once per frame
	void Update () {

        headLayer1StateInfo = headAnimator.GetCurrentAnimatorStateInfo(1);
        //headLayer0StateInfo = headAnimator.GetCurrentAnimatorStateInfo(0);

        // If we press the fire button and are not currently firing...
	    if(Input.GetButtonDown("Fire1") && headLayer1StateInfo.shortNameHash != fireWeaponStateHash) {
            //Debug.Log("Firing!");

            //firing = true;
            // Create invisible line that actually causes things to explode.
            //ShootLine();
            mover.Shoot();

            // Play animation on camera to simulate gun recoil.
            //AddCamRecoil();

            // Create lazor effect.
            //StartCoroutine(ImmaFirinMahLazor());

            // Play a cool sound!
            //PlayLazorSound(); 

            // Add a particle effect!
        }

        

        //if(firing && headStateInfo.shortNameHash == fireWeaponStateHash) {
        //    firing = false;
        //}

        // Handle aiming down sights
        if(Input.GetButtonDown("Fire2"))
            gunAnimator.SetBool(aimBoolHash, true);

        if(Input.GetButtonUp("Fire2"))
            gunAnimator.SetBool(aimBoolHash, false);

        if(Input.GetButton("Fire2")) {
            playerCamera.fieldOfView = Mathf.Lerp(playerCamera.fieldOfView, aimFOV, fovChangeSpeed * Time.deltaTime);
        }
        else if(playerCamera.fieldOfView != defaultFOV){
            playerCamera.fieldOfView = Mathf.Lerp(playerCamera.fieldOfView, defaultFOV, fovChangeSpeed * Time.deltaTime);
        }
	}
    
    void ShootLine() {
        RaycastHit hit;
        Ray dir = Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f));

        if(Physics.Raycast(dir, out hit)) {
            // Make a neat little spark where we hit stuff!
            Instantiate(lazorParticle, hit.point, Quaternion.identity);

            if(hit.collider.gameObject.tag == "Destructible") {
                hit.collider.gameObject.GetComponent<ParticleDestructibleObject>().TakeExplodyDamage(gunDamage);
            }
        }
    }

    public void AddCamRecoil() {
        headAnimator.SetTrigger(fireTriggerHash);
    }

    IEnumerator ImmaFirinMahLazor() {
        gunLazor.enabled = true;

        gunLazor.material.SetTextureOffset("_MainTex", new Vector2(Time.time, 0));

        yield return new WaitForSeconds(lazorDuration);

        gunLazor.enabled = false;
    }

    void PlayLazorSound() {
        source.PlayOneShot(lazorSounds[Random.Range(0, lazorSounds.Length - 1)]);
    }
}
