using System.Collections.Generic;
using UnityEngine;

namespace ScrambleKit.Move.AI
{
    [RequireComponent(typeof(MoveCore))]
    public class AITopDownChase : MonoBehaviour
    {
        public Transform Target;

        private MoveCore core;
        private const string MOVELEFT = "MoveLeft";
        private const string MOVERIGHT = "MoveRight";
        private const string MOVEUP = "MoveUp";
        private const string MOVEDOWN = "MoveDown";

        private Dictionary<string, bool> wantsToMove = new Dictionary<string, bool>();


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

        void FixedUpdate()
        {
            if (Target == null)
                return;

            PlanToChaseTarget();
            UpdateInputs();
        }

        private void PlanToChaseTarget()
        {
            wantsToMove[MOVELEFT] = Target.position.x < transform.position.x;
            wantsToMove[MOVERIGHT] = Target.position.x > transform.position.x;
            wantsToMove[MOVEUP] = Target.position.y > transform.position.y;
            wantsToMove[MOVEDOWN] = Target.position.y < transform.position.y;
        }

        private void UpdateInputs()
        {
            foreach(string move in wantsToMove.Keys)
            {
                SetInput(move, wantsToMove[move]);
            }
        }

        private void SetInput(string move, bool wantHeld)
        {
            bool held = core.input.CheckHeld(move);

            if (wantHeld && !held)
                core.input.AIHold(move);

            if (!wantHeld && held)
                core.input.AIRelease(move);

        }

    }

}