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

using Hanna.Controls;


namespace Medivators.Reporting
{
	public partial class ucAutoRefresh : Shape
	{
		private int _interval = 120;
		private DateTime _lastRefresh = DateTime.Now;

		public delegate void AutoRefreshTimerElapsedEventHandler(object sender, System.EventArgs e);
		public event AutoRefreshTimerElapsedEventHandler AutoRefreshTimerElapsed;
		
		public ucAutoRefresh()
		{
			InitializeComponent();
		}
		
		public bool AutoRefreshEnabled
		{
			get { return this.checkAutoRefresh.Checked; }
			set 
			{
				this.checkAutoRefresh.Checked = value;
				ToggleEnabled();
			}
		}

		public int RefreshInterval
		{
			get { return _interval; }
			set { _interval = value; }
		}

		private void refreshTimer_Tick(object sender, EventArgs e)
		{
			if (DateTime.Now.CompareTo(_lastRefresh.AddSeconds(_interval)) >= 0)
				RefreshNow();
			this.lblNext.Text = string.Format("Next  {0}:{1}",
										  ((TimeSpan)DateTime.Now.Subtract(_lastRefresh.AddSeconds(_interval))).Minutes * -1,
										  (((TimeSpan)DateTime.Now.Subtract(_lastRefresh.AddSeconds(_interval))).Seconds * -1).ToString("00"));
		}

		private void checkAutoRefresh_CheckedChanged(object sender, EventArgs e)
		{
			ToggleEnabled();			
		}

		private void btnRefreshNow_Click(object sender, EventArgs e)
		{
			RefreshNow();
		}
		private void RefreshNow()
		{
			this.AutoRefreshTimerElapsed(this, new EventArgs());
			_lastRefresh = DateTime.Now;
		}
		private void ToggleEnabled()
		{
			this.refreshTimer.Enabled = this.checkAutoRefresh.Checked;
			if (!this.checkAutoRefresh.Checked)
				this.lblNext.Text = "Next  OFF";
		}
	}
}
