using UnityEngine;
using Saltosion.OneWeapon.Guns;

namespace Saltosion.OneWeapon.AI.Behaviours {
    [RequireComponent(typeof(Follow))]
    public class RangedAttackFollowed : AIBehaviour {
        public GameObject BulletPrefab;
        public float Range;
        public float Cooldown;

        public bool Attacking { get { return CanBehave(); } }

        private Follow Follow;

        private float CurrentCooldown;

        private void Start() {
            Follow = GetComponent<Follow>();
        }

        private void Update() {
            if (CurrentCooldown > 0) {
                CurrentCooldown -= Time.deltaTime;
            }
        }

        public override bool CanBehave() {
            return Follow.Target != null && Follow.GetDistance() <= Range;
        }

        public override void Execute() {
            CurrentStatus = "PewPew";
            if (CurrentCooldown <= 0) {
                Shoot();
                CurrentCooldown = Cooldown;
                CurrentStatus = "PEW"; // A joke that lasts for a frame
            }
        }

        private void Shoot() {
            Vector2 Direction = Follow.TargetDirection.normalized;
            GameObject ShotBulletObj = Instantiate(BulletPrefab, transform.position + (Vector3)Direction, new Quaternion());
            Bullet ShotBullet = ShotBulletObj.GetComponent<Bullet>();
            ShotBullet.Direction = Direction;
            ShotBullet.InitialRotation = Mathf.Atan2(Direction.y, Direction.x);
        }

        private void OnDrawGizmosSelected() {
            Gizmos.color = Color.red;
            Gizmos.DrawWireSphere(transform.position, Range);
        }
    }
}
