using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace MemoQServicesClient
{
    public static class Log
    {
        static RichTextBox logTextBox;
        const int numOfMaxChars = 500000;
        public static readonly string MajorSeparatorLine = "********************************************************";
        public static readonly string MinorSeparatorLine = "--------------------------------------------------------";

        public static void Init(RichTextBox logTextBox)
        {
            Log.logTextBox = logTextBox;
        }

        public static void WriteMajorSeparatorLine()
        {
            WriteLine(MajorSeparatorLine);
        }

        public static void WriteMinorSeparatorLine()
        {
            WriteLine(MinorSeparatorLine);
        }

        public static void WriteLine(string text)
        {
            Write(text + Environment.NewLine);
        }

        public static void Write(string text)
        {
            bool scrollToLast = logTextBox.SelectionStart == logTextBox.Text.Length;
            int caretpos = logTextBox.SelectionStart;

            // Unfortunaltely this always scrolls to the last position.
            // More unfortunately this ignores RichText.MaxLength, so can not be used at all.
            //log.AppendText( entry.ToString() );
            logTextBox.Text += text;

            //const int numOfLinesToRemoveInOneIteration = 50;
            const int numOfCharsToRemoveInOneIteration = numOfMaxChars > 5000 ? 5000 : numOfMaxChars;

            if (logTextBox.Text.Length > numOfMaxChars)
                logTextBox.Text = logTextBox.Text.Substring(numOfCharsToRemoveInOneIteration);

            if (scrollToLast)
            {
                logTextBox.SelectionStart = logTextBox.Text.Length;
            }
            else
                logTextBox.SelectionStart = caretpos;

            logTextBox.ScrollToCaret();
        }

    }
}
