using System.Collections.Generic;
using UnityEngine;

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

        private MoveCore core;
        private Vector2 dir;

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

            core.Animate("Jump");
            CheckWalkDir();
            if (dir != Vector2.zero)
                Move();
            else
                Stop();
        }

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

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

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

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

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

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