using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class Player : MonoBehaviour {

    public int[] weapons;
    public int[] mag;
    public int[] maxMag;
    public int[] ammo;
    public int[] startingAmmo;
    public int[] maxAmmo;
    public int[] weaponDamage;
    public float[] reloadTimes;

    public int health = 6;
    public bool canPickup = false;
    public int pickupId = 0;
    public bool pickupUsed = false;
    public int pickupMagCount = 0;

    private Vector3 movement;
    private float direction = 0;
    public int currentWeapon = 0;
    private bool canFire = true;
    private bool reloading = false;
    private float reloadTimer = 0;
    private float bulletTime = 0;
    private float bulletFireRate = 0;

    public string weaponToPickup = "";

    private AudioClip pistolShot;
    private AudioClip pistolReload;
    private AudioClip shotgunShot;
    private AudioClip shotgunReload;
    private AudioClip sniperShot;
    private AudioClip sniperReload;
    private AudioSource audioSource;
    private AudioClip hit;

    private Rigidbody rb;

    // Use this for initialization
    void Start() {
        weapons = new int[2] { 0, 0 };
        mag = new int[4] { 8, 0, 0, 0 };
        maxMag = new int[4] { 8, 25, 1, 6 };
        ammo = new int[4] { 0, 0, 0, 0 };
        maxAmmo = new int[4] { 0, 200, 18, 60 };
        startingAmmo = new int[4] { 0, 75, 8, 18 };
        reloadTimes = new float[4] { .5f, 1, 2, 1.5f };
        weaponDamage = new int[4] { 2, 1, 10, 2 };
        rb = GetComponent<Rigidbody>();
        movement = Vector3.zero;

        pistolShot = Resources.Load<AudioClip>("Sounds/pistolshot");
        pistolReload = Resources.Load<AudioClip>("Sounds/pistolreload");
        shotgunShot = Resources.Load<AudioClip>("Sounds/shotgunshot");
        shotgunReload = Resources.Load<AudioClip>("Sounds/shotgunreload");
        sniperShot = Resources.Load<AudioClip>("Sounds/snipershot");
        sniperReload = Resources.Load<AudioClip>("Sounds/sniperreload");
        hit = Resources.Load<AudioClip>("Sounds/hit");

        audioSource = GetComponent<AudioSource>();
}
	
	// Update is called once per frame
	void Update () {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit = new RaycastHit();
        if (Physics.Raycast(ray, out hit, 100))
        {
            Vector3 hitPoint = hit.point;

            Vector3 targetDir = hitPoint - transform.position;

            direction = (Mathf.Atan2(targetDir.z, targetDir.x) * Mathf.Rad2Deg) - 180;
        }

        float moveHorizontal = (Input.GetKey(KeyCode.D) ? 1 : 0) - (Input.GetKey(KeyCode.A) ? 1 : 0);
        float moveVertical = (Input.GetKey(KeyCode.W) ? 1 : 0) - (Input.GetKey(KeyCode.S) ? 1 : 0);
        if (moveHorizontal != 0 && moveVertical != 0)
        {
            float mult = (1 / Mathf.Sqrt(2));
            moveHorizontal *= mult;
            moveVertical *= mult;
        }
        movement = new Vector3(moveHorizontal, 0, moveVertical);
        rb.velocity = movement * 1000 * Time.deltaTime;

        if (Input.GetMouseButtonDown(1))
        {
            rb.velocity = movement * 2000 * Time.deltaTime;
        }

        //Switch weapons if scrolling and you don't only have a pistol
        if (scrolling() && (weapons[1] != 0))
        {
            //If currentWeapon is 0, change it to 1, and vice versa
            currentWeapon = currentWeapon == 0 ? 1 : 0;
        }

        //If you press reload and you aren't already reloading, puts you into the reload state
        if (Input.GetKeyDown(KeyCode.R) && !reloading)
        {
            reloading = true;
            switch (weapons[currentWeapon])
            {
                case 0:
                    audioSource.PlayOneShot(pistolReload);
                    break;
                case 1:
                    audioSource.PlayOneShot(pistolReload);
                    break;
                case 2:
                    audioSource.PlayOneShot(sniperReload);
                    break;
                case 3:
                    audioSource.PlayOneShot(shotgunReload);
                    break;
                default:
                    break;
            }
        }
        if (reloading)
        {
            reloadTimer += Time.deltaTime;
            if (reloadTimer > reloadTimes[weapons[currentWeapon]])
            {
                if (weapons[currentWeapon] == 0)
                {
                    mag[weapons[currentWeapon]] = maxMag[weapons[currentWeapon]];
                }
                else
                {
                    int neededAmmo = maxMag[weapons[currentWeapon]] - mag[weapons[currentWeapon]];
                    if (ammo[weapons[currentWeapon]] > neededAmmo)
                    {
                        mag[weapons[currentWeapon]] = maxMag[weapons[currentWeapon]];
                        ammo[weapons[currentWeapon]] -= neededAmmo;
                    }
                    else
                    {
                        mag[weapons[currentWeapon]] += ammo[weapons[currentWeapon]];
                        ammo[weapons[currentWeapon]] = 0;
                    }
                }
                reloading = false;
                reloadTimer = 0;
                canFire = true;
                bulletTime = 0;
            }
        }

        if (canPickup)
        {
            if (Input.GetKeyDown(KeyCode.E))
            {
                //If a weapon.... do weapon things
                if (pickupId > 0 && pickupId < 4)
                {
                    //Add ammo to weapon if it's a weapon we already ahve
                    if (weapons[0] == pickupId || weapons[1] == pickupId)
                    {
                        ammo[pickupId] += startingAmmo[pickupId];
                        if (ammo[pickupId] > maxAmmo[pickupId])
                            ammo[pickupId] = maxAmmo[pickupId];
                    }
                    else
                    {
                        //Equip the weapon if it's our first secondary weapon, or replace the current weapon if it's not
                        if (weapons[0] == 0 && weapons[1] == 0)
                        {
                            weapons[1] = pickupId;
                            currentWeapon = 1;
                        } else
                        {
                            weapons[currentWeapon] = pickupId;
                        }
                        mag[pickupId] = pickupMagCount;
                        if (!pickupUsed)
                        {
                            ammo[pickupId] = startingAmmo[pickupId];
                        }
                    }
                }
            }
        }

        if (health <= 0)
        {
            SceneManager.LoadScene("GameOver");
        }

        //transform.position = this.transform.position + movement;
        movement = Vector3.zero;
        handleWeapons();
    }

    float AngleBetweenTwoPoints(Vector3 a, Vector3 b)
    {
        return Mathf.Atan2(a.z - b.z, a.x - b.x) * Mathf.Rad2Deg;
    }

    void handleWeapons()
    {
        bulletTime += Time.deltaTime;
        switch(weapons[currentWeapon])
        {
            case 0:
                bulletFireRate = .35f;
                break;
            case 1:
                bulletFireRate = .1f;
                break;
            case 2:
                bulletFireRate = .1f;
                break;
            case 3:
                bulletFireRate = .5f;
                break;
            default: break;
        }
        if (bulletTime > bulletFireRate)
        {
            bulletTime -= bulletFireRate;
            canFire = true;
        }
        if (Input.GetMouseButton(0) && canFire && mag[weapons[currentWeapon]] > 0 && !reloading)
        {
            switch (weapons[currentWeapon])
            {
                case 0:
                    spawnBullet(direction, 2);
                    audioSource.PlayOneShot(pistolShot);
                    break;
                case 1:
                    spawnBullet(direction + Random.Range(-3f, 3f), 1);
                    audioSource.PlayOneShot(pistolShot);
                    break;
                case 2:
                    spawnBullet(direction, 20);
                    audioSource.PlayOneShot(sniperShot);
                    break;
                case 3:
                    for (int i = 0; i < 7; i++)
                        spawnBullet(direction + Random.Range(-15f, 15f), 2);
                    audioSource.PlayOneShot(shotgunShot);
                    break;
                default:
                    break;
            }
            canFire = false;
            mag[weapons[currentWeapon]]--;
        }
    }

    void spawnBullet(float direction, float damage)
    {
        GameObject bullet = Instantiate(Resources.Load("Bullet", typeof(GameObject))) as GameObject;
        bullet.transform.position = transform.position;
        bullet.transform.rotation = transform.rotation;
        BulletBehavior bb = bullet.GetComponent<BulletBehavior>();
        bb.direction = direction - 180;
        bb.damage = weaponDamage[weapons[currentWeapon]];
        Physics.IgnoreCollision(bullet.GetComponent<Collider>(), GetComponent<Collider>());
    }

    bool scrolling()
    {
        return Input.GetAxis("Mouse ScrollWheel") != 0;
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == "pickup")
        {
			WeaponPickUpScript wps = other.gameObject.GetComponent<WeaponPickUpScript>();
			pickupId = wps.id;
			//If ammo, increase ammo
			if (pickupId == 4 && weapons[currentWeapon] != 0)
			{
				ammo[weapons[currentWeapon]] += startingAmmo[weapons[currentWeapon]];
				if (ammo[weapons[currentWeapon]] > maxAmmo[weapons[currentWeapon]])
					ammo[weapons[currentWeapon]] = maxAmmo[weapons[currentWeapon]];
			}
			//If health, increase health
			if (pickupId == 5)
			{
				health += 2;
				if (health > 6)
					health = 6;
			}
            canPickup = true;

            pickupUsed = wps.used;
            pickupMagCount = wps.magCount;
        }
    }

    private void OnTriggerExit(Collider other)
    {
        if (other.gameObject.tag == "pickup")
        {
            weaponToPickup = "";
            canPickup = false;
            pickupId = 0;
            pickupUsed = false;
            pickupMagCount = 0;
        }
    }

    private void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.tag == "EnemyBullet")
        {
            audioSource.PlayOneShot(hit);
            health--;
        }
    }
}