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

namespace Rokojori
{
  public class TextLine
  {
    public readonly int characterIndex;
    public readonly int length; 
    public readonly int lineIndex;
    public readonly int lineBreakLength;

    public TextLine( int lineIndex, int characterIndex, int length, int lineBreakLength )
    {
      this.characterIndex = characterIndex;
      this.length = length;
      this.lineIndex = lineIndex;
      this.lineBreakLength = lineBreakLength;
    }

    public int contentLength { get { return length - lineBreakLength; }  }
    public int contentOffset { get { return characterIndex + lineBreakLength; } }
    public int textEditorLineIndex { get { return lineIndex + 1 ; } }
    
    public string GetContent( string source )
    {
      return source.Substring( contentOffset, contentLength );
    }


    public string info 
    {
      get 
      {
        var info = new List<string>();

        info.AddRange(  new List<string>{
          "line index: " + lineIndex,
          "character index: " + characterIndex,
          "content length: " + contentLength,
          "length: " + length,
          "line break length: " + lineBreakLength          
          }
        );

        return "{ " + Lists.Join( info, ", " ) + " }";

      }
    }

    

    public TextAnchor GetRawAnchor( int characterIndex )
    {
      return new TextAnchor( lineIndex, characterIndex - this.characterIndex );
    } 
    
    public TextAnchor GetTextEditorAnchor( int characterIndex )
    {
      var lineOffset = this.characterIndex + lineBreakLength;
      var offset = Mathf.Max( 0, characterIndex - lineOffset );
      return new TextAnchor( lineIndex + 1, offset + 1 );
    } 

    public int lineStart { get { return characterIndex; } }
    public int lineEnd { get { return ( characterIndex + length ); } }

    public bool Contains( int characterIndex )
    {
      return lineStart <= characterIndex && characterIndex <= lineEnd;
    }
           
  }
}