using Godot;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Rokojori
{
  public class NavigationMap
  {
    public Rid map;
    public Rid region;

    public Vector3[] GetPath( Vector3 start, Vector3 end )
    {
      return NavigationServer3D.MapGetPath( map, start, end, true );
    }


    public static async Task<NavigationMap> Create( Node node, NavigationMesh mesh )
    {
      RJLog.Log( "Creating map" );

      var map = NavigationServer3D.MapCreate();
      NavigationServer3D.MapSetUp( map, Vector3.Up );
      NavigationServer3D.MapSetActive( map, true );

      var mapReady = false;

      NavigationServer3D.MapChanged += ( map )=>
      { 
        RJLog.Log( "Map was changed", map );
        mapReady = true;
      };


      RJLog.Log( "Creating region" );
      var region = NavigationServer3D.RegionCreate();
      NavigationServer3D.RegionSetTransform( region, Transform3D.Identity );      
      NavigationServer3D.RegionSetMap( region, map );


      RJLog.Log( "Creating mesh" );
      NavigationServer3D.RegionSetNavigationMesh( region, mesh );

      
      RJLog.Log( "Waiting for Navigation Server" );
      
      var waits = 0;
      var maxWaits = 100;

      while ( ! mapReady && waits < maxWaits )
      {
        await Task.Delay( 10 );
        waits ++;
      }

      //await node.ToSignal( node.GetTree(), SceneTree.SignalName.PhysicsFrame );

    

      RJLog.Log( "Map Created" );
      var mapData = new NavigationMap();
      
      mapData.map = map;
      mapData.region = region;
      

      return mapData; 
    }
  }
}