using ScrambleKit.Game;
using ScrambleKit.Hits;
using UnityEngine;

public class ChargeAttack : MonoBehaviour 
{
    public float ChargeDuration = 0.5f;
    public float ChargeSpeed = 16f;
    public Transform HurtBoxToDisable;

    private float stopAttackingAt;
    private bool attacking;
    private Rigidbody2D rb;
    private EnemyMovementController move;
    private Vector2 attackDir;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        move = GetComponent<EnemyMovementController>();
    }

    void PerformAttack()
    {
        StartAttacking();
    }

    void LandedHit(HitInfo hit)
    {
        StopAttacking();
    }

    void TakeHit(HitInfo hit)
    {
        StopAttacking();
    }

    void FixedUpdate()
    {
        if (!attacking)
            return;
        
        if(Time.fixedTime > stopAttackingAt)
        {
            StopAttacking();
        }
        else
        {
            UpdateCharge();
        }
    }

    private void StartAttacking()
    {
        attacking = true;
        stopAttackingAt = Time.fixedTime + ChargeDuration;
        attackDir = (GameInfo.Player.position - transform.position).normalized;

        move.TargetPos = GameInfo.Player.position;  //causes facing toward dash

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

    private void StopAttacking()
    {
        attacking = false;
        move.TargetPos = transform.position;
        FullStop();

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

    private void FullStop()
    {
        Vector2 stopForce = rb.mass * -rb.velocity;
        rb.AddForce(stopForce);
    }

    private void UpdateCharge()
    {
        Vector2 targetSpeed = attackDir * ChargeSpeed;
        Vector2 accel = targetSpeed - rb.velocity;
        Vector2 force = rb.mass * accel / Time.fixedDeltaTime;
        rb.AddForce(force);
    }

}
