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

namespace Rokojori
{

  [GlobalClass,Icon("res://addons/rokojori_action_library/Icons/Grabber.svg")]
  public partial class Grabber:Node3D, SensorInputHandler
  {
    [Export]
    public Sensor button;

    [Export]
    public Pointer pointer;

    [Export]
    public TimeLine timeLine;
    
    [Export]
    public Node3D grabOffset;

    [ExportGroup("Read Only")]
    [Export]
    public Grabbable grabbable;


    public override void _Ready()
    {
      SensorManager.Register( this, button );
    }

    public override void _ExitTree()
    {
      SensorManager.Unregister( this, button );
    }

    TimeLineCallback _callback = null;

    public void _OnSensor( SensorEvent se )
    {
      if ( se.isDown && _callback == null )
      {
        StartGrabbing();
      }
      else if ( se.isUp && _callback != null )
      {
        ReleaseGrabbing();
      }
    }

    void StartGrabbing()
    {
      var pointable = pointer.pointable;

      if ( pointable == null )
      {
        return;
      }

      var grabbable = Nodes.Find<Grabbable>( pointable.GetParent() );

      if ( grabbable == null )
      {
        return;
      }

      grabbable.SetGrabber( this );

      _callback = TimeLineManager.ScheduleCallback( timeLine, 
        ( cb )=>
        {
          if ( cb != _callback )
          {
            return;
          }
          
          UpdateGrabbable();
        } 
      );
    }

    void ReleaseGrabbing()
    {
      _callback.done = true;
      _callback = null;
    }

    void UpdateGrabbable()
    {

    }

  }
}