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

public class SequenceAttack : ChargeAttack
{
    [SerializeField]
    private Transform[] _directions;

    void Start()
    {
        Transform directions = transform.FindChild("Directions");
        _directions = new Transform[directions.childCount];

        for(int i = 0; i < directions.childCount; i++)
        {
            _directions[i] = directions.GetChild(i);
        }
    }

    public override void OnButtonReleased(PlayerController player)
    {
        float totalChargeTime = (Time.time - _startChargeTime) / ChargeTime;
        totalChargeTime = Mathf.Clamp(totalChargeTime, _timeThreshold, 1);

        _charge = totalChargeTime;

        StartCoroutine(ExecuteCoroutine(player));        
    }

    protected override void Execute(PlayerController player, Vector3 spawnPos)
    {
        Wave spawnedWave = Instantiate(Wave.gameObject, spawnPos, Quaternion.identity).GetComponent<Wave>();
        spawnedWave.Launch(GetRandomDirection().right);

        player.Rigidbody.AddForce(player.Transform.right * _knockBack);
    }

    private IEnumerator ExecuteCoroutine(PlayerController player)
    {
        float duration = _charge * 5;
        int steps = Mathf.FloorToInt(_charge * 30);

        _shootTime = Time.time;

        float waitTime = duration / steps;

        for (int i = 0; i < steps; i++)
        {
            Execute(player, player.ShootingPoint.position);
            yield return new WaitForSeconds(waitTime);
        }

        State = AttackState.COOLDOWN;
        player.OnCooldownStarted();
    }

    private Transform GetRandomDirection()
    {
        int index = Random.Range(0, _directions.Length);

        return _directions[index];
    }
}
