using Godot;
using System.Collections;
using System.Collections.Generic;
using Godot.Collections;

namespace Rokojori
{

  [GlobalClass,Icon("res://addons/rokojori_action_library/Icons/Pointable.svg")]
  public partial class Pointable:Node3D
  {
    [Export]
    public int pointingPriority;

    [Export]
    public Action onPointed;

    [Export]
    public Action onUnpointed;
    
    [Export]
    public Action onPointerAdded;
    
    [Export]
    public Action onPointerRemoved;

    [ExportGroup("Highlighting")]
    [Export]
    public HighlightEffect highlightEffect;

    [Export]
    public Node3D[] highlightTargets = new Node3D[ 0 ];


    [ExportGroup("Read Only")]
    [Export]
    public Pointer[] pointers = new Pointer[ 0 ];

    List<Pointer> _pointers = new List<Pointer>();

    public int numPointing => _pointers.Count;

    public bool IsPointedBy( Pointer pointer )
    {
      return _pointers.Contains( pointer );
    }

    public void UpdatePointerState( Pointer pointer, bool pointed )
    {
      var isCurrentlyPointed = IsPointedBy( pointer );

      if ( isCurrentlyPointed == pointed )
      {
        return;
      }


      if ( pointed )
      { 
        _pointers.Add( pointer );
        Action.Trigger( onPointerAdded );

        if ( _pointers.Count == 1 )
        {
          Action.Trigger( onPointed );
        }

      }
      else 
      {
        _pointers.Remove( pointer );

        Action.Trigger( onPointerRemoved );

        if ( _pointers.Count == 0 )
        {
          Action.Trigger( onUnpointed );
        } 

      }

      pointers = _pointers.ToArray();
      

    }
  }
}