using OpenSEMI.Ctrlib.Types;
using System.Windows;
using System.Windows.Controls;

namespace OpenSEMI.Ctrlib.Controls
{
	public class Valve : Button
	{
		public static readonly DependencyProperty ValveStateProperty;

		public static readonly DependencyProperty ValueProperty;

		public static readonly DependencyProperty OrientationProperty;

		private ValveLogicType m_ValveLogic = ValveLogicType.Positive;

		public ValveState ValveState
		{
			get
			{
				return (ValveState)GetValue(ValveStateProperty);
			}
			set
			{
				SetValue(ValveStateProperty, value);
			}
		}

		public int Value
		{
			get
			{
				return (int)GetValue(ValueProperty);
			}
			set
			{
				SetValue(ValueProperty, value);
			}
		}

		public Orientation Orientation
		{
			get
			{
				return (Orientation)GetValue(OrientationProperty);
			}
			set
			{
				SetValue(OrientationProperty, value);
			}
		}

		public ValveLogicType ValveLogic
		{
			get
			{
				return m_ValveLogic;
			}
			set
			{
				m_ValveLogic = value;
			}
		}

		static Valve()
		{
			ValveStateProperty = DependencyProperty.Register("ValveState", typeof(ValveState), typeof(Valve), new UIPropertyMetadata(ValveState.UNKNOWN));
			ValueProperty = DependencyProperty.Register("Value", typeof(int), typeof(Valve), new UIPropertyMetadata(-1, ValueChangedCallBack));
			OrientationProperty = DependencyProperty.Register("Orientation", typeof(Orientation), typeof(Valve), new UIPropertyMetadata(Orientation.Vertical));
			FrameworkElement.DefaultStyleKeyProperty.OverrideMetadata(typeof(Valve), new FrameworkPropertyMetadata(typeof(Valve)));
		}

		public override void OnApplyTemplate()
		{
			base.OnApplyTemplate();
			SetValveState(this);
		}

		public static void ValueChangedCallBack(DependencyObject d, DependencyPropertyChangedEventArgs args)
		{
			Valve valve = d as Valve;
			if (valve != null)
			{
				SetValveState(valve);
			}
		}

		private static void SetValveState(Valve v)
		{
			if (v.Value == 0)
			{
				if (v.ValveLogic == ValveLogicType.Positive)
				{
					v.ValveState = ValveState.OFF;
				}
				else
				{
					v.ValveState = ValveState.ON;
				}
			}
			else if (v.Value == 1)
			{
				if (v.ValveLogic == ValveLogicType.Positive)
				{
					v.ValveState = ValveState.ON;
				}
				else
				{
					v.ValveState = ValveState.OFF;
				}
			}
			else
			{
				v.ValveState = ValveState.UNKNOWN;
			}
		}
	}
}