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

public class enemy : MonoBehaviour
{
    private Rigidbody2D _rb;

    public Transform bulletPoint;
    public GameObject bullet;

    private int Currentammo = 5;
    private int maxAmmo = 5;

    private float moveSpeed = 60f;
    private float jumpForce = 400f;

    private int storeRandNum;

    private bool canShoot;
    private bool isGrounded;

    // Start is called before the first frame update
    void Start()
    {
        _rb = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        Debug.Log(storeRandNum);
        randActions();
        storeRandNum = Random.Range(0, 30);
        shooting();
        
        if (Currentammo == 0)
        {
            Invoke("reload", 3f);
        }

    }

    void shooting() 
    {
        if (Currentammo != 0 && canShoot == true) 
        {
            GameObject instantiatedBullet = Instantiate(bullet, bulletPoint.position, Quaternion.identity);
            Rigidbody2D rigidbody = instantiatedBullet.GetComponent<Rigidbody2D>();
            rigidbody.AddForce(Vector2.right * 500f);
            Destroy(instantiatedBullet, 2f);
            StartCoroutine(controleShooting());
            canShoot = false;

            Currentammo--;
        }
        
    }

    void reload() 
    {
            Currentammo = maxAmmo;
    }

    void runRight() 
    {
        float right = 1;
        Vector3 movementRight = new Vector3(right, 0f, 0f) * moveSpeed * Time.deltaTime;
        transform.position += movementRight;
    }

   void runLeft()
    {
        float left = -1f;
        Vector3 movementLeft = new Vector3(left, 0f, 0f) * moveSpeed * Time.deltaTime;
        transform.position += movementLeft;

    }

    void jump() 
    {
        float y = 1f;
        Vector3 _jump = new Vector3(0f, y, 0f) * jumpForce * Time.deltaTime;
        transform.position += _jump;
        isGrounded = false;
    }

    void randActions() 
    {
        if (storeRandNum == 1) 
        {
            runRight();
        }
        else if(storeRandNum == 10) 
        {
            runLeft();
        }
        else if (storeRandNum == 29 && isGrounded) 
        {
            jump();
        }
      
    }

    private IEnumerator controleShooting()
    {
        canShoot = true;
        yield return new WaitForSeconds(1f);
        canShoot = false;
    }

    private void OnCollisionEnter2D(Collision2D col)
    {
        if (col.gameObject.CompareTag("ground"))
        {
            isGrounded = true;
        }
    }



}