using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Threading;

namespace Olympics
{
    public partial class Clock : UserControl
    {
        public Clock()
        {
            InitializeComponent();

            if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
            {
                Thread thread = new Thread(new ThreadStart(RunClock));
                thread.Start();
            }
        }

        private delegate void UpdateUIDelegate();
        private Timer _timer;

        private void RunClock()
        {
            _timer = new Timer(
                new TimerCallback((target) => 
                { 
                    var action = new UpdateUIDelegate(UpdateClock);
                    Dispatcher.BeginInvoke(action);
                }), 
                null, 
                TimeSpan.FromSeconds(0), 
                TimeSpan.FromSeconds(1))
                ;
        }

        private void UpdateClock()
        {

            DateTime utcTime = TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.Utc);

            clockHours.Value = (utcTime.Hour + 8) % 12;
            clockMins.Value = utcTime.Minute;
            clockSecs.Value = utcTime.Second;

            // fire time changed event
            if (TimeChanged != null)
            {
                TimeChanged(this, new TimeChangedEventArgs()
                {
                    Hour = (int)clockHours.Value,
                    Minute = (int)clockMins.Value,
                    Second = (int)clockSecs.Value
                });
            }
        }

        public event EventHandler<TimeChangedEventArgs> TimeChanged;
    }

    public class TimeChangedEventArgs
        : EventArgs
    {
        public int Second { get; set;  }
        public int Minute { get; set; }
        public int Hour { get; set; }
    }
}
