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

public class PlayerController : MonoBehaviour
{
    [SerializeField] float xMoveSpeed;
    [SerializeField] float yMoveSpeed;
    [SerializeField] float zMoveSpeed;

    Rigidbody myRigidBody;

    [SerializeField] GameObject bombPrefab;

    private GameManager myGameManager;

    [SerializeField] private int maxBombs = 2;
    private int currentBombsPlaced = 0;

    private bool hasControl = true;
    [SerializeField] private float destroyTime = 2f;


    // Start is called before the first frame update
    void Start()
    {
        myRigidBody = GetComponent<Rigidbody>();
        myGameManager = FindObjectOfType<GameManager>();

    }

    // Update is called once per frame
    void Update()
    {
        if(hasControl)
        {
            Movement();
            PlaceBomb();
        }

    }

    void Movement()
    {
        Vector3 newVelocity = new Vector3();

        if (Input.GetKey(KeyCode.W))
        {
            newVelocity = new Vector3(0f, 0f, zMoveSpeed);
        }
        else if (Input.GetKey(KeyCode.S))
        {
            newVelocity = new Vector3(0f, 0f, -zMoveSpeed);
        }
        else if (Input.GetKey(KeyCode.A))
        {
            newVelocity = new Vector3(-xMoveSpeed, 0f, 0f);
        }
        else if (Input.GetKey(KeyCode.D))
        {
            newVelocity = new Vector3(xMoveSpeed, 0f, 0f);
        }

        myRigidBody.velocity = newVelocity;

    }

    private void PlaceBomb()
    {
        if(Input.GetKeyDown(KeyCode.Space) && currentBombsPlaced < maxBombs)
        {
            GameObject bomb = Instantiate(bombPrefab, transform.position, Quaternion.identity);
            bomb.transform.position = new Vector3(Mathf.Round(transform.position.x), 0f, Mathf.Round(transform.position.z));
            currentBombsPlaced++;
        }
    }

    public void Defeated()
    {
        hasControl = false;

        Destroy(gameObject, destroyTime);

        myGameManager.PlayerDefeated();
    }

    private void OnCollisionEnter(Collision collision)
    {
        if(collision.gameObject.tag == "Enemy")
        {
            Defeated();
        }
    }

    public void BombExploded()
    {
        currentBombsPlaced--;
    }

    public float GetDestroyDelayTime()
    {
        return destroyTime;
    }


}
