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

public class Rocket : MonoBehaviour
{
    public PoweredObject power;
    [Header("Values")]
    [Tooltip("Delay before return power")]
    public float delayAfterFire = 2f;
    public Transform rocketPosition;
    public Transform rocketSprite;


    [Space(5)]
    [Header("Values")]
    public float scanRadius = 50;
    public LayerMask senseMask;
    Transform targetPosition;

    [Space(5)]
    public Transform bulletPrefab;

    bool finishCoolDown = true;
    // Use this for initialization
    void Start()
    {
        power = rocketPosition.GetComponent<PoweredObject>();
    }

    void SensingEnemy()
    {
        if (targetPosition == null)
        {
            Collider2D[] overlapList = Physics2D.OverlapCircleAll(transform.position, scanRadius, senseMask);

            foreach (Collider2D other in overlapList)
            {
                if (other.gameObject != gameObject)
                {
                    targetPosition = other.transform;
                }
            }
        }
    }

    public void Fire()
    {
        if (finishCoolDown == false)
        {
            return;
        }

        SensingEnemy();

        if (bulletPrefab != null)
        {
            RocketBullet bullet = Instantiate(bulletPrefab, rocketPosition.position, Quaternion.Euler(0, 0, 90)).gameObject.GetComponent<RocketBullet>();
            if (bullet != null)
            {
                if (targetPosition != null)
                    bullet.targetPosition = targetPosition.position;
                else
                    bullet.targetPosition = transform.position;
                bullet.owner = gameObject;
            }

        }
        if (rocketSprite != null)
            rocketSprite.gameObject.SetActive(false);

        finishCoolDown = false;
        Invoke("CoolDown", delayAfterFire);
    }

    void CoolDown()
    {
        finishCoolDown = true;

        if (rocketSprite != null)
            rocketSprite.gameObject.SetActive(true);
    }

    public bool IsFinishCoolDown()
    {
        return finishCoolDown;
    }
}
