using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class Weapon : MonoBehaviour {

    public GameObject bulletPrefab;

    public Transform muzzle;

    public float attackDelay = 0.8f;

    public float ammo = float.PositiveInfinity;

    float timeBeforeAttack;

    public GameObject graphicsPrefab;

    public AudioClip fireSound;

    AudioManager audioMan;

    GameObject graphics;


    public void Init(Transform playerGraphics)
    {
        graphics = GameObject.Instantiate(graphicsPrefab, playerGraphics);
        audioMan = GameObject.FindGameObjectWithTag("GameController").GetComponent<AudioManager>();
        timeBeforeAttack = attackDelay;
    }

    public bool CheckWindow()
    {
        PointerEventData pointer = new PointerEventData(EventSystem.current);
        pointer.position = Input.mousePosition;
        List<RaycastResult> results = new List<RaycastResult>();
        EventSystem.current.RaycastAll(pointer, results);

        if (results == null || results.Count == 0)
            return true;

        foreach (RaycastResult result in results)
        {
            //if (result.gameObject.layer != 13)
            //    return false;
            if (result.gameObject.GetComponent<Button>() != null)
                return false;
        }
        return true;
    }
	
	// Update is called once per frame
	void Update () {
        timeBeforeAttack = Mathf.Max(0, timeBeforeAttack - Time.deltaTime);

        if (timeBeforeAttack == 0 && Input.GetButton("Fire") && CheckWindow())
        {
            if (fireSound != null)
            {
                audioMan.Play(fireSound, muzzle.transform.position, Random.Range(0.7f, 1.3f));
            }
            Fire();

            if (ammo <= 0)
                GetComponentInParent<Player>().SwitchWeapon(null);
            timeBeforeAttack = attackDelay;
        }
        else
            DontFire();
	}

    protected virtual void Fire()
    {
        GameObject.Instantiate(bulletPrefab, muzzle.position, muzzle.rotation);
        ammo--;
    }

    protected virtual void DontFire()
    {
    }

    void OnDestroy()
    {
        if (graphics != null)
            GameObject.Destroy(graphics);
    }
}
