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

public class Tank2Shoot : MonoBehaviour {

    public static Tank2Shoot instance;
    
    public GameObject tank2Bullet;
    private float timeToShoot = 1f;
    private float timeToShootNext = 2f;
    
    public GameObject player;
    private int damageToPlayer = 5;
    public PlayerHealth playerHealth;
    
    void Start () {
        player = GameObject.FindGameObjectWithTag("Player");
        playerHealth = player.GetComponent<PlayerHealth>();
        MakeInstance();
    }

    void MakeInstance() {
        if (instance == null) {
            instance = this;
        }
    }

    void Update () {
        float distance = Vector3.Distance(player.transform.position, transform.position);

        if (distance < 10) {
            AttackPlayer();
        }

        if (distance < 7) {
            EnemyTank.instance.speed = 0;
        }
    }

    void AttackPlayer() {
        if (Time.time >= timeToShoot) {
            EnemyTank2Shoot();
            timeToShoot = Time.time + timeToShootNext;
        }
    }
    
    public void DamageToPlayerByTank2() {
        if (playerHealth.currentHealth > 0) {
            playerHealth.PlayerDamage(damageToPlayer);

        } else if (playerHealth.currentHealth == 0) {
          
        }
    }

    void EnemyTank2Shoot() {
        GameObject player = GameObject.Find("Player");
        if (player != null) {
            GameObject bullet = Instantiate(tank2Bullet, transform.position, transform.rotation) as GameObject;
            Vector2 direction = player.transform.position - bullet.transform.position;
            bullet.GetComponent<Tank1Bullet>().SetBulletDirection(direction);
            Destroy(bullet, 1.5f);
        }
        
    }
}
