using Godot;
using System.Collections.Generic;

namespace Rokojori
{  
  public enum SceneFileValueType
  {
    Variant,
    ExtResource,
    SubResource,
    NodePath
  }

  public class SceneFileValue
  {
    public SceneFileValueType type;
    public Variant variant;
    public string reference;

    public static readonly List<SceneFileValueType> referenceTypes = new List<SceneFileValueType>
    {
      SceneFileValueType.ExtResource,
      SceneFileValueType.SubResource,
      SceneFileValueType.NodePath
    };

    public static readonly List<string> referenceStringTypes = Lists.Map( 
      referenceTypes, ( s, i ) => s + ""
    );


    public void ParseValue( List<LexerEvent> tokens, int start, int length )
    {     

      var startToken = tokens[ start ];
      var startTokenInfo = LexerEvent.GetMatchFromRange( tokens, start, length );

      // RJLog.Log( "ParseValue", startToken.type, startToken.IsAny( LexerMatcherLibrary.CwordMatcher ), startTokenInfo );

      if ( startToken.IsAny( LexerMatcherLibrary.CFunctionMatcher ) )
      {
        var referenceStringIndex = referenceStringTypes.IndexOf( startToken.match );

        if ( referenceStringIndex != -1 )
        { 
          type = referenceTypes[ referenceStringIndex ];
          reference = JSONStringConverter.Read( tokens[ start + 2 ].match );

          // RJLog.Log( "Reference type:", type, reference );
      
          return;
        }        

        // RJLog.Log( "Not a reference type:", startToken );
      }

      type = SceneFileValueType.Variant;

      variant = VariantFromTokens( tokens, start, length );
      
      //RJLog.Log( "Variant type:", variant );
    }

    public static Variant VariantFromTokens( List<LexerEvent> tokens, int start, int length )
    {
      var startToken = tokens[ start ];

      if ( length == 1 )
      {
        if ( startToken.Is( LexerMatcherLibrary.NumberMatcher ) )
        {
          return Variant.From(  RegexUtility.ParseDouble( startToken.match ) );
        }  

        if ( startToken.Is( LexerMatcherLibrary.DoubleQuotedStringMatcher ) )
        {
          return Variant.From( JSONStringConverter.Read( startToken.match ) );
        }

        if ( startToken.IsAny( LexerMatcherLibrary.CwordMatcher, "true", "false" ) )
        {
          return Variant.From( startToken.match == "true" ) ;
        }
      } 

      return Variant.From( "" );
    } 

  
  }
}