using AI.Base;
using UnityEditor.Experimental.GraphView;
using UnityEngine;
using static TMPro.SpriteAssetUtilities.TexturePacker_JsonArray;

public class EnemyStateManager : StateManager {
  [Header("States")]
  [SerializeField] public StateNode WalkState;
  [SerializeField] public StateNode ChaseState;
  [SerializeField] public StateNode AttackState;
  [SerializeField] public StateNode DamagedState;

  [Header("Attributes")]
  [SerializeField] private float ChaseDistance = 10f;
  [SerializeField] private float AttackDistance = 1f;

  private Transform Player;
   

  protected void Start() {
    Player = GameObject.FindGameObjectWithTag("Player")?.transform;
    WalkState = ScriptableObject.CreateInstance(WalkState.GetType()) as StateNode;

    WalkState = WalkState.InitializeCopy(this.transform);
    ChaseState = ChaseState.InitializeCopy(this.transform);
    //DamagedState = DamagedState.InitializeCopy(this.transform);
    AttackState = AttackState.InitializeCopy(this.transform);

    AttackState.Initialize(this.transform);

    CurrentState = WalkState;
    CurrentState.Start();
  }

  protected void InitializeStateNode(StateNode node){
    node = ScriptableObject.CreateInstance(node.GetType()) as StateNode;
    node.Initialize(this.transform);
  }

  override protected IState GetNextState() {
    if (Player == null)
      return CurrentState;

    float dist = Vector2.Distance(transform.position, Player.position);
    if (dist < AttackDistance)
      return AttackState.GetNextState();
    else if (dist < ChaseDistance)
      return ChaseState.GetNextState();
    else
      return WalkState.GetNextState();
  }







  private void OnDrawGizmos() {
    DrawChaseDistance();
    DrawAttackDistance();
  }
  private void DrawChaseDistance() {
    Gizmos.color = CurrentState == (IState)ChaseState ? Color.yellow : Color.green;
    Vector2 center = this.transform.position;
    Gizmos.DrawWireSphere(center, ChaseDistance);
  }
  private void DrawAttackDistance() {
    Gizmos.color = CurrentState == (IState)AttackState ? Color.red : Color.green;
    Vector2 center = this.transform.position;
    Gizmos.DrawWireSphere(center, AttackDistance);
  }
}
