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

namespace PhidgetsControlLibrary {
	public partial class PropertySlider : UserControl {
		double minValue = 0;
		double maxValue = 99;
		double propertyValue = 0;
		bool isFloat = false;
		string unit = "";
		string name = "Property Name:";
		private Font startingSmallFont;
		private float startingDpi;
		public PropertySlider() {
			InitializeComponent();
			startingSmallFont = minLbl.Font;
			startingDpi = DeviceDpi;
		}

		public event EventHandler SetClick {
			add { setBtn.Click += value; }
			remove { setBtn.Click -= value; }
		}

		public event KeyEventHandler SetEnter {
			add { valueTxt.KeyDown += value; }
			remove { valueTxt.KeyDown -= value; }
		}

		public event EventHandler TrackScroll {
			add { valueTrk.Scroll += value; }
			remove { valueTrk.Scroll -= value; }
		}

		public event MouseEventHandler TrackMouseUp {
			add { valueTrk.MouseUp += value; }
			remove { valueTrk.MouseUp -= value; }
		}

		#region properties
		public double Minimum {
			get {
				return this.minValue;
			}
			set {
				this.minValue = value;
				minLbl.Text = value.ToString("F0");
			}
		}

		public double Maximum {
			get {
				return this.maxValue;
			}
			set {
				this.maxValue = value;
				maxLbl.Text = value.ToString("F0");
			}
		}

		public bool IsFloat { get { return isFloat; } set { isFloat = value; } }
		public string Unit { get { return unit; } set { unit = value; } }

		public double Value {
			get {
				return propertyValue;
			}
			set {
				propertyValue = value;
				valueTxt.Text = value.ToString() + unit;
				valueTrk.Value = (int)(value / (maxValue - minValue) * 100);
			}
		}

		public string TrackText {
			get { return valueTxt.Text; }
			set { valueTxt.Text = value.ToString(); }
		}

		public string LabelText {
			get { return name; }
			set {
				name = value;
				label.Text = name;
			}
		}

		#endregion

		private void setBtn_Click(object sender, EventArgs e) {
			setValue();
		}

		private void valueTxt_KeyDown(object sender, KeyEventArgs e) {
			try {
				if (e.KeyCode == Keys.Enter) {
					e.SuppressKeyPress = true;
					setValue();
				}
			} catch { }
		}

		private void setValue() {
			try {
				propertyValue = double.Parse(valueTxt.Text);
				valueTrk.Value = (int)((propertyValue / (maxValue - minValue)) * 100.0);
			} catch { }
		}

		private void valueTrk_Scroll(object sender, EventArgs e) {
			try {
				propertyValue = (((double)valueTrk.Value) / 100 * (maxValue - minValue));
				if (!isFloat)
					propertyValue = (int)propertyValue;
				valueTxt.Text = propertyValue.ToString() + unit;
			} catch { }
		}

		private void PropertySlider_DpiChangedAfterParent(object sender, EventArgs e) {
			float factor = DeviceDpi / startingDpi;
			var smallFont = new Font(startingSmallFont.FontFamily, startingSmallFont.Size * factor, startingSmallFont.Style);
			minLbl.Font = smallFont;
			maxLbl.Font = smallFont;
			setBtn.Font = smallFont;
		}
	}
}
