using ScrambleKit.Hits;
using ScrambleKit.Move;
using UnityEngine;

public class EnemyMovementController : MonoBehaviour 
{
    public float MoveAcceleration = 40;
    public float StopDeceleration = 50;
    public float SpeedLimit = 6;
    public bool UpdateFacing = true;

    public Vector2 TargetPos;
    
    private Rigidbody2D rb;
    private Vector2 dir;
    private float stunnedUntil;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        TargetPos = transform.position;  // TODO This is a test line
    }

    void TakeHit(HitInfo hit)
    {
        stunnedUntil = Mathf.Max(stunnedUntil, Time.fixedTime + hit.StunTime);
    }

    public void FixedUpdate()
    {
        if (stunnedUntil > Time.fixedTime)
            return;

        CheckWalkDir();
        if (dir != Vector2.zero)
            Move();
        else
            Stop();
    }

    private void Move()
    {
        if (UpdateFacing)
        {
            if (dir.x < 0)
                transform.localScale = new Vector3(-1, 1, 1);
            else
                transform.localScale = new Vector3(1, 1, 1);
        }

        rb.AccelTowardVelocityByAtMost(SpeedLimit * dir, MoveAcceleration);
    }

    private void Stop()
    {
        rb.AccelTowardVelocityByAtMost(Vector2.zero, StopDeceleration);
    }

    private void CheckWalkDir() 
	{
        Vector2 pos = transform.position;
        Vector2 diff = TargetPos - pos;

        if (diff.magnitude < 0.1f)
            dir = Vector2.zero;
        else
            dir = diff.normalized;
	}
}
