using System.Collections;
using System.Collections.Generic;
using Unity.IO.LowLevel.Unsafe;
using UnityEngine;

//Ben Keller
public class Shooting : MonoBehaviour
{
    private Camera mainCam;
    private Vector3 mousePos;

    public GameObject bulletPref;
    public Transform bulletTransform;
    public bool canFire;
    private float timer;
    
    public PlayerStats playerStats;

    SpriteRenderer spriteRenderer;

    public Transform muzzle;


    void Start()
    {
        mainCam = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Camera>();
        playerStats = gameObject.GetComponentInParent<PlayerStats>();
        spriteRenderer = gameObject.GetComponentInChildren<SpriteRenderer>();
    }


    void Update()
    {
        mousePos = mainCam.ScreenToWorldPoint(Input.mousePosition);

        Vector3 rotation = mousePos - transform.position;

        float rotZ = Mathf.Atan2(rotation.y, rotation.x) * Mathf.Rad2Deg;

        transform.rotation = Quaternion.Euler(0, 0, rotZ);

        flip();

        fire();
    }

    void flip(){
                if (mousePos.x < transform.position.x)
        {
            spriteRenderer.flipY = true;
            muzzle.localPosition = new Vector3(1.65f, -0.14f, 0);
        }
        else
        {
            spriteRenderer.flipY = false;
            muzzle.localPosition = new Vector3(1.65f, 0.14f, 0);
        }
    }

    void fire(){
        if(!canFire){
            timer += Time.deltaTime;
            if(timer > playerStats.fireRate){
                canFire = true;
                timer = 0;
            }
        }

        if(Input.GetMouseButton(0) && canFire){
            canFire = false;
            Instantiate(bulletPref, bulletTransform.position, Quaternion.identity);
        }
    }
}
