using UnityEngine;

namespace ScrambleKit.Move.AI
{
    [RequireComponent(typeof(MoveCore))]
    public class AIWalkBackAndForth : MonoBehaviour
    {
        public float MinSwitchInterval = 0.1f;

        private MoveCore core;
        private const string MOVELEFT = "MoveLeft";
        private const string MOVERIGHT = "MoveRight";

        private string direction = MOVELEFT;
        private float lastSwitched;

        void Start()
        {            
            core = GetComponent<MoveCore>();
            lastSwitched = Time.fixedTime;
        }

        void FixedUpdate()
        {
            core.input.AIHold(direction);
            if (BumpedWall())
                ReverseDirection();
        }

        private void ReverseDirection()
        {
            lastSwitched = Time.fixedTime;
            core.input.AIRelease(direction);
            direction = (direction == MOVERIGHT) ? MOVELEFT : MOVERIGHT;
            core.input.AIHold(direction);
        }

        private bool BumpedWall()
        {
            return (Time.fixedTime - lastSwitched > MinSwitchInterval) && core.rb2.velocity.magnitude <= 0.01f;
        }

    }

}