namespace mgaia.Utils.Text
{
    /// <summary>
    /// Interpretador de texto para o formato de label multicolorido
    /// </summary>
    /// <owner>Victor</owner>
    public class ColoredTextInterpreter : ITextInterpreter
    {
        private string mText;
        private int mCurrentIdx;

        private const char OPENING_COLOR_IDENTIFIER = '{';
        private const char ENDING_COLOR_IDENTIFIER = '}';

        public void Begin(string text)
        {
            mText = text;
            mCurrentIdx = 0;
        }

        public int GetTextSize()
        {
            int size = 0;

            bool isInColorIdentifier = false;
            foreach (char currentChar in mText)
            {
                if (currentChar == OPENING_COLOR_IDENTIFIER)
                {
                    isInColorIdentifier = true;
                }
                else if (currentChar == ENDING_COLOR_IDENTIFIER)
                {
                    isInColorIdentifier = false;
                }
                else
                {
                    if (!isInColorIdentifier)
                    {
                        size++;
                    }
                }
            }

            return size;
        }

        public string GetNextFragmentToWrite()
        {
            if (mCurrentIdx < mText.Length)
            {
                string stringToWrite = string.Empty;

                char charAtIndex = mText[mCurrentIdx];

                if (charAtIndex == OPENING_COLOR_IDENTIFIER)
                {
                    bool wroteLegalCharacter = false;
                    bool wroteEndingColorIdentifier = false;
                    while (!wroteLegalCharacter || mCurrentIdx == mText.Length)
                    {
                        stringToWrite += charAtIndex;

                        if (charAtIndex == ENDING_COLOR_IDENTIFIER)
                        {
                            wroteEndingColorIdentifier = true;
                        }
                        else if (wroteEndingColorIdentifier)
                        {
                            wroteLegalCharacter = true;
                        }

                        charAtIndex = mText[++mCurrentIdx];
                    }

                    return stringToWrite;
                }
                else
                {
                    Assert.AssertTrue(charAtIndex != OPENING_COLOR_IDENTIFIER && charAtIndex != ENDING_COLOR_IDENTIFIER, "Esse caractere não devia ser escrito aqui, ocorreu algum problema no algoritmo!");

                    return mText[mCurrentIdx++].ToString();
                }
            }
            else
            {
                return null;
            }
        }
    }
}