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

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

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

    public static async Task<NavigationMap2D> Create( Node node, List<Path2> regions )
    {
      var map = NavigationServer2D.MapCreate();
      NavigationServer2D.MapSetActive( map, true );

      var cellSize = NavigationServer2D.MapGetCellSize( map );

      
      var region = NavigationServer2D.RegionCreate();
      NavigationServer2D.RegionSetTransform( region, Transform2D.Identity );
      
      NavigationServer2D.RegionSetMap( region, map );

      var polygon = new NavigationPolygon();
      // polygon.SetCe
      for ( int i = 0; i < 1 && i < regions.Count; i++ )
      {
        regions[ i ].AddToNavigationPolygon( polygon );
      }

      NavigationServer2D.RegionSetNavigationPolygon( region, polygon );

      await node.ToSignal( node.GetTree(), SceneTree.SignalName.PhysicsFrame );
      
      var mapData = new NavigationMap2D();
      
      mapData.map = map;
      mapData.region = region;
      

      return mapData;
    }
  }
}