using System;
using Quadarax.Foundation.Core.Object;

namespace Quadarax.Foundation.Core.Console
{
    public class ConsoleWriter : DisposableObject
    {
        private readonly ConsoleColor _oldBackColor;
        private readonly ConsoleColor _oldForeColor;
        private readonly ConsoleColor _backColor;
        private readonly ConsoleColor _foreColor;


        public ConsoleWriter(ConsoleColor foreColor,ConsoleColor backColor)
        {
            _oldBackColor = System.Console.BackgroundColor;
            _oldForeColor = System.Console.ForegroundColor;
            _backColor = backColor;
            _foreColor = foreColor;
        }

        public ConsoleWriter(ConsoleColor foreColor)
        {
            _oldBackColor = System.Console.BackgroundColor;
            _oldForeColor = System.Console.ForegroundColor;
            _backColor = _oldBackColor;
            _foreColor = foreColor;
        }


        public ConsoleWriter WriteLine(string text)
        {
            SetColor();
            WriteInternal(text);
            WriteLineInternal();
            return this;
        }

        public string? ReadLine()
        {
            SetColor();
            return System.Console.ReadLine();
        }

        public ConsoleWriter WriteLine()
        {
            WriteLineInternal();
            return this;
        }
        public ConsoleWriter Write(string text)
        {
            SetColor();
            WriteInternal(text);
            return this;
        }

        public static void Clear()
        {
            System.Console.Clear();
        }

        protected virtual void WriteInternal(string text)
        {
            System.Console.Write(text);
        }
        protected virtual void WriteLineInternal()
        {
            System.Console.WriteLine();
        }

        protected override void OnDisposing()
        {
            System.Console.ForegroundColor = _oldForeColor;
            System.Console.BackgroundColor = _oldBackColor;
        }

        private void SetColor()
        {
            System.Console.ForegroundColor = _foreColor;
            System.Console.BackgroundColor = _backColor;
        }

    }
}
