using System.Text;

namespace NubLang.Generation;

internal class IndentedTextWriter
{
    private readonly StringBuilder _builder = new();
    private int _indentLevel;

    public IDisposable Indent()
    {
        _indentLevel++;
        return new IndentScope(this);
    }

    public void WriteLine(string text)
    {
        WriteIndent();
        _builder.AppendLine(text);
    }

    public void Write(string text)
    {
        WriteIndent();
        _builder.Append(text);
    }

    public void WriteLine()
    {
        _builder.AppendLine();
    }

    public override string ToString()
    {
        return _builder.ToString();
    }

    private void WriteIndent()
    {
        if (_builder.Length > 0)
        {
            var lastChar = _builder[^1];
            if (lastChar != '\n' && lastChar != '\r')
                return;
        }

        for (var i = 0; i < _indentLevel; i++)
        {
            _builder.Append("    ");
        }
    }

    private class IndentScope : IDisposable
    {
        private readonly IndentedTextWriter _writer;
        private bool _disposed;

        public IndentScope(IndentedTextWriter writer)
        {
            _writer = writer;
        }

        public void Dispose()
        {
            if (_disposed) return;
            _writer._indentLevel--;
            _disposed = true;
        }
    }
}