using Godot;
using System.Text;
using System.Collections.Generic;
using System.Linq;

namespace Rokojori
{  
  public class HierarchyName
  {
    public static string OfAny( object obj, string seperator = " ▸ " )
    {
      if ( obj is Resource r )
      {
        return Of( r, seperator );
      }
      
      if ( obj is Node n )
      {
        return Of( n, seperator );
      }

      return RJLog.Stringify( obj ); 
    }

    public static string Of( Resource resource, string seperator = " ▸ " )
    {
      var path = resource.ResourcePath;

      path = RegexUtility.Replace( path, "::.*$", "" );
      path = RegexUtility.Replace( path, "^res:\\/\\/", "" );

      var splitted = RegexUtility.SplitPaths( path );


      var sb = new StringBuilder();

      for ( int i = 0; i < splitted.Count; i++ )
      {
        if ( i !=  0 )
        {
          sb.Append( seperator );
        }

        sb.Append( splitted[ i ] );
      }

      return sb.ToString();

    }

    public static string Of( Node[] nodes, string seperator = " ▸ " )
    { 
      return "{\n" + nodes.ToList().Map( n => Of( n, seperator ) ).Join( "\n" ) + "\n}"; 
    }

    public static string Of( Node node, string seperator = " ▸ " )
    {
      if ( node == null )
      {
        return "null";
      }

      var list = new List<string>();

      var it = node;

      while ( it != null )
      {
        var n = it.Name;

        if ( RegexUtility.Matching( n, @"@\d+$" ) )
        {
          it = null;
        }
        else
        {
          list.Add( it.Name );
          it = it.GetParent();
        }        
      }

      list.Reverse();


      var sb = new StringBuilder();

      for ( int i = 0; i < list.Count; i++)
      {
        if ( i != 0 )
        {
          sb.Append( seperator );
        }

        sb.Append( list[ i ] );
      }

      return sb.ToString();
    }
  }

}
