using System.Windows.Forms;

namespace GlobalSever.Form
{
    public class UILog
    {
        private const int MaxLines = 100;
        private TextBox _textBox;
        
        public UILog()
        {
            
        }

        public UILog(TextBox textBox)
        {
            _textBox = textBox;
        }

        public void Debug(string text)
        {
            if (_textBox == null)
            {
                return;
            }

            string message = $"{System.DateTime.Now:yyyy-MM-dd HH:mm:ss.fff} {text}{System.Environment.NewLine}";

            if (_textBox.InvokeRequired)
            {
                _textBox.BeginInvoke(new System.Action(() =>
                {
                    _textBox.AppendText(message);
                    TrimExcessLines();
                }));
                return;
            }

            _textBox.AppendText(message);
            TrimExcessLines();
        }

        public void Clear()
        {
            if (_textBox == null)
            {
                return;
            }

            if (_textBox.InvokeRequired)
            {
                _textBox.BeginInvoke(new System.Action(() => _textBox.Clear()));
                return;
            }

            _textBox.Clear();
        }

        private void TrimExcessLines()
        {
            string[] lines = _textBox.Lines;
            if (lines.Length <= MaxLines)
            {
                return;
            }

            int keep = MaxLines;
            int start = lines.Length - keep;
            string[] trimmed = new string[keep];
            System.Array.Copy(lines, start, trimmed, 0, keep);
            _textBox.Lines = trimmed;
            _textBox.SelectionStart = _textBox.TextLength;
            _textBox.ScrollToCaret();
        }
    }
}
