/**************************************************** 
 文件：EditorWindowLayout.cs
 作者：张铮
 邮箱：834207172@qq.com
 日期：2022/3/3 17:53:52
 功能：
*****************************************************/
using System;
using System.Text;
namespace Stary.Evo.Editor
{
    public class ScriptBuilder
    {
        private readonly string NEW_LINE = Environment.NewLine;

        public ScriptBuilder()
        {
            builder = new StringBuilder();
        }

        private StringBuilder builder;
        public int Indent { get; set; }

        private int currentCharIndex;

        public void Write(string val, bool noAutoIndent = false)
        {
            if (!noAutoIndent)
                val = GetIndents() + val;
            if (currentCharIndex == builder.Length)
                builder.Append(val);
            else
                builder.Insert(currentCharIndex, val);
            currentCharIndex += val.Length;
        }

        public void WriteLine(string val, bool noAutoIndent = false)
        {
            Write(val + NEW_LINE);
        }

        public int WriteCurlyBrackets(bool increaseIndent = false)
        {
            var openBracket = GetIndents() + "{" + NEW_LINE;
            var closeBracket = GetIndents() + "}" + NEW_LINE;
            Write(openBracket + closeBracket, true);
            currentCharIndex -= closeBracket.Length;
            if(increaseIndent)
                Indent++;
            return closeBracket.Length;
        }

        public void GetOutOfCurlyBrackets(int lastCurlyBracketSize, bool decreaseIndent = false)
        {
            currentCharIndex += lastCurlyBracketSize;
            if (decreaseIndent)
                Indent--;
        }

        public string GetIndents()
        {
            var str = "";
            for (var i = 0; i < Indent; i++)
                str += "    ";
            return str;
        }

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