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

public class Gun : MonoBehaviour
{
    // Start is called before the first frame update
    public GameObject BulletPrefab, SpawnPoint;
    float cooltime;
    Animator animcont;
    void Start()
    {
        // transform.parent = GameObject.Find("GunHolder").transform;
        cooltime = Time.time;
        animcont = gameObject.GetComponent<Animator>();
        animcont.SetFloat("Idle", 1);
    }

    private void FixedUpdate()
    {
        if (Input.GetMouseButton(0))
        {
            if(Camera.main.ScreenToWorldPoint(Input.mousePosition).y < 0)
            {
                //Debug.Log("sa");
                transform.position = new Vector3(transform.position.x, transform.position.y, -2);
            }
            if (Camera.main.ScreenToWorldPoint(Input.mousePosition).y > 0)
            {
                //Debug.Log("as");
                transform.position = new Vector3(transform.position.x, transform.position.y, 1);
            }
            Vector3 dir = Input.mousePosition - Camera.main.WorldToScreenPoint(transform.position);
            float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
            transform.parent.transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
            if(cooltime < Time.time)
            {
                StartCoroutine(ShootRoutine());
                GameObject bullet = Instantiate(BulletPrefab, SpawnPoint.transform.position, Quaternion.Euler(0,0,0));
                Vector3 ShootAngle = Camera.main.ScreenToWorldPoint(Input.mousePosition) - SpawnPoint.transform.position;
                bullet.GetComponent<Rigidbody2D>().velocity = ShootAngle * 5f;
                cooltime = Time.time + 0.2f;
            }
            

        }
        if (Input.GetKey(KeyCode.W))
        {
            transform.position = new Vector3(transform.position.x, transform.position.y, 1);
        }
        if (Input.GetKey(KeyCode.S))
        {
            transform.position = new Vector3(transform.position.x, transform.position.y, -2);
        }
       
    }

    IEnumerator ShootRoutine()
    {
        
        //Debug.Log(animcont.GetFloat("Idle"));
        animcont.SetFloat("Shoot", 1);
        yield return new WaitForSecondsRealtime(0.5f);
        animcont.SetFloat("Shoot", -1);
    }
}
