using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

namespace RyzStudio.Windows.Forms
{
	public partial class TCustomProgressBar : TUserControl
	{
		protected int minimum = 0;
		protected int maximum = 100;
		protected int value = 50;


		public TCustomProgressBar() : base()
		{
			InitializeComponent();

			this.Padding = new Padding(0);
		}


        [Category("Data"), Browsable(true)]
		public int Minimum
		{
			get => minimum;
			set
			{
				if (this.InvokeRequired)
				{
					this.Invoke(new MethodInvoker(() => {
						SetMinimum(value);
					}));
				}
				else
				{
					SetMinimum(value);
				}
			}
		}

		[Category("Data"), Browsable(true)]
		public int Maximum
		{
			get => maximum;
			set
			{
				if (this.InvokeRequired)
				{
					this.Invoke(new MethodInvoker(() => {
						SetMaximum(value);
					}));
				}
				else
				{
					SetMaximum(value);
				}
			}
		}

		[Category("Data"), Browsable(true)]
		public int Value
		{
			get => value;
			set
			{
				if (this.InvokeRequired)
				{
					this.Invoke(new MethodInvoker(() => {
						SetValue(value);
					}));
				}
				else
				{
					SetValue(value);
				}
			}
		}

        [Category("Appearance"), Browsable(true)]
		public Color BarColour { get; set; } = Color.FromArgb(158, 225, 249);

        [Category("Appearance"), Browsable(true)]
		public Color BarTextColour { get => label3.ForeColor; set => label3.ForeColor = value; }


		protected override void OnPaint(PaintEventArgs e)
		{
			base.OnPaint(e);

			Rectangle canvas = this.DisplayRectangle;
			Graphics g = e.Graphics;

			if (this.Value > 0)
			{
				decimal result = decimal.Divide(canvas.Width, this.Maximum) * this.Value;

				canvas.Width = (int)Math.Round(result);

				g.FillRectangle(new SolidBrush(this.BarColour), canvas);
			}
		}


		public void Reset(int value)
        {
			this.Minimum = 0;
			this.Value = 0;
			this.Maximum = value;
		}

		protected void UpdateText() => RyzStudio.Windows.Forms.ThreadControl.SetText(label3, string.Format("{0}/{1}", this.Value.ToString(), this.Maximum.ToString()));

		protected void SetMinimum(int value)
		{
			int m = value;
			if (m < 0) m = 0;
			if (m > this.Maximum) m = this.Maximum;
			if (this.Value < m) this.Value = m;
			if (this.value > this.Maximum) this.value = this.Maximum;

			minimum = m;

			UpdateText();

			this.Invalidate();
		}

		protected void SetMaximum(int value)
		{
			int m = value;
			if (m < 0) m = 0;
			if (m < this.Minimum) m = this.Minimum;
			if (this.Value > m) this.Value = m;
			if (this.value < this.Minimum) this.value = this.Minimum;

			maximum = m;

			UpdateText();

			this.Invalidate();
		}

		protected void SetValue(int value)
		{
			int m = value;
			if (m < this.Minimum) m = this.Minimum;
			if (m > this.Maximum) m = this.Maximum;

			this.value = m;

			UpdateText();

			this.Invalidate();
		}

	}
}