using System;
using System.Text;

namespace Quadarax.Foundation.Core.Console
{
    public class ProgressConsoleWriter : ConsoleWriter
    {
        #region *** Private Fields ***
        private readonly int _maxProgress;
        private int _curProgress = 0;
        private string _lastText = string.Empty;
        #endregion

        #region *** Constructors ***
        public ProgressConsoleWriter(ConsoleColor foreColor, ConsoleColor backColor, int maxProgress) : base(foreColor, backColor)
        {
            _maxProgress = maxProgress;
        }

        public ProgressConsoleWriter(ConsoleColor foreColor, int maxProgress) : base(foreColor)
        {
            _maxProgress = maxProgress;
        }
        #endregion

        #region *** Public Operations ***

        public void SetProgress(int progress)
        {
            _curProgress = progress;
            OnRefreshProgress();
        }
        public void IncProgress()
        {
            _curProgress++;
            OnRefreshProgress();
        }
        public void DecProgress()
        {
            _curProgress--;
            OnRefreshProgress();
        }
        
        #endregion

        #region *** Internal Operations ***

        protected override void WriteLineInternal()
        {
            base.WriteLineInternal();
            OnRefreshProgress();
        }

        protected override void WriteInternal(string text)
        {
            _lastText = text;
            OnRefreshProgress();
        }

        private void OnRefreshProgress()
        {
            base.WriteInternal("\r");
            base.WriteInternal(new string(' ', System.Console.BufferWidth - 1));
            base.WriteInternal("\r");
            var sb = new StringBuilder();
            sb.Append("[").Append(_curProgress).Append("/").Append(_maxProgress).Append("] ").Append(_lastText);
            base.WriteInternal(sb.ToString());
        }
        protected override void OnDisposing()
        {
            System.Console.WriteLine();
            base.OnDisposing();
        }

        #endregion

    }
}
