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

public class TankShoot : MonoBehaviour {

    public static TankShoot instance;

    public GameObject tankBullet;
    private float timeToShoot = 1f;
    private float timeToShootNext = 2f;

    public GameObject player;
    private int damageToPlayer = 2;
    public PlayerHealth playerHealth;

	void Awake () {
        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) {
            EnemyTankShoot();
            timeToShoot = Time.time + timeToShootNext;
        }
    }

    public void DamageToPlayerByTank1() {
        if (playerHealth.currentHealth > 0) {
            playerHealth.PlayerDamage(damageToPlayer);

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

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