using System.Collections.Generic;
using UnityEngine;

namespace ScrambleKit.Move.Platformer
{
    [RequireComponent(typeof(MoveCore))]
    public class PlatformerWalkMove : MonoBehaviour
    {
        public float MoveAcceleration = 40;
        public float StopDeceleration = 50;
        public float SpeedLimit = 6;

        private MoveCore core;
        private Vector2 dir;

        public void FixedUpdate()
        {
            if (!core.IsTouchingGround())
                return;

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

        private void Move()
        {
            core.Animate("Walk");
            core.FaceXDirection(dir.x);

            Vector2 targetVel = new Vector2(SpeedLimit * dir.x, core.rb2.velocity.y);
            core.rb2.AccelTowardVelocityByAtMost(targetVel, MoveAcceleration);
        }

        private void Stop()
        {
            core.Animate("Idle");

            Vector2 targetVel = new Vector2(0, core.rb2.velocity.y);
            core.rb2.AccelTowardVelocityByAtMost(targetVel, StopDeceleration);
        }        

        private void CheckWalkDir()
        {
            dir = Vector2.zero;
            if (core.input.CheckHeld(InputNames.MOVELEFT))
                dir = Vector2.left;
            if(core.input.CheckHeld(InputNames.MOVERIGHT))
                dir = Vector2.right;
        }

        void AddBindingNames(HashSet<string> bindingNames)
        {
            bindingNames.Add(InputNames.MOVELEFT);
            bindingNames.Add(InputNames.MOVERIGHT);
        }

        void Start()
        {
            core = GetComponent<MoveCore>();
        }
    }
}
