using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class OutputController : MonoBehaviour {

    public UnityEngine.UI.Text textField;
    public UnityEngine.UI.Text backupField;
    public int maxLines;
    int currentLines = 0;

    public string errorColor = "#ff0000ff";
    public string outputColor = "#ffffffff";
    public string inputColor = "#999999ff";

    public static OutputController instance { get; private set; }

    public void Awake()
    {
        instance = this;
    }

    public enum MessageType
    {
        Error, Output, Input
    }

    public void Log(string s, MessageType type)
    {
        string textColor;
        switch (type)
        {
            case MessageType.Error:
                textColor = errorColor;
                break;
            case MessageType.Output:
                textColor = outputColor;
                break;
            case MessageType.Input:
                textColor = inputColor;
                break;
            default:
                textColor = "#00ff00ff";
                break;
        }

        if (textField.isActiveAndEnabled)
        {
            int numLines = s.Length - s.Replace(System.Environment.NewLine, string.Empty).Length;
            currentLines++;

            while (currentLines > maxLines)
            {
                currentLines--;
                // remove the first line
                int i = textField.text.IndexOf(System.Environment.NewLine);
                textField.text = textField.text.Substring(i + System.Environment.NewLine.Length);
            }
            // add a colored line to the end
            var reader = new System.IO.StringReader(s);
            string line = string.Empty;
            do
            {
                line = reader.ReadLine();
                textField.text += System.Environment.NewLine;
                textField.text += "<color=" + textColor + ">" + line + "</color>";
            } while (line != null);
        }
        else
        {
            StopAllCoroutines();
            backupField.enabled = true;
            backupField.text = "<color=" + textColor + ">" + s + "</color>";
            StartCoroutine(WaitForClose(2));
        }
    }

    IEnumerator WaitForClose(float s)
    {
        yield return new WaitForSeconds(s);
        backupField.enabled = false;
    }
}
