using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Serialization;

using System;
using System.Text;
using System.Collections;

using Random = UnityEngine.Random;

public class ManagerLog : MonoBehaviour 
{
    #region 变量

    private Text LogText;
    private ScrollRect LogScrollRect;

    private int LogCount;
    private int LogCapacityInitial;
    private bool ShowBottom;

    public static ManagerLog Ins;

    #endregion

    private void Start()
    {
        ShowBottom = true;
    }

    private void Awake()
    {
        LogText = ManagerResource.Ins.LogLabel;
        LogScrollRect = ManagerResource.Ins.LogScrollRect;

        Ins = this;

        LogCapacityInitial = LogText.text.Split('\n').Length;
    }

    private void FixedUpdate()
    {
        if (ShowBottom)
        {
            ShowBottom = false;
            LogScrollRect.verticalNormalizedPosition = 0;
        }
    }


    public  void AddMessage(string message)
    {
        if (LogCount < LogCapacityInitial)
        {
            string[] contents = LogText.text.Split('\n');

            LogText.text = "";
            Sort(contents, message);

            for (int i = 0; i < LogCapacityInitial; i++)
            {
                if (i == LogCapacityInitial - 1)
                {
                    LogText.text = LogText.text + contents[i];
                }
                else
                {
                    LogText.text = LogText.text + contents[i] + '\n';
                }
            }
        }
        else
        {
            LogText.text = LogText.text + '\n' + message;
        }

        LogCount++;

        if (Math.Abs(LogScrollRect.verticalNormalizedPosition) < 0.01f)
        {
            ShowBottom = true;
        }
    }

    private void Sort(string[] strings, string message)
    {
        for (int i = 0; i < strings.Length - 1; i++)
        {
            strings[i] = strings[i + 1];
        }

        strings[strings.Length - 1] = message;
    }
}