using System;
using Microsoft.SPOT;

using Microsoft.SPOT.Hardware;

using System.Text;

using GHI.Premium.Hardware;

namespace miniCPF
{
    class CPFUtilities
    {

        private static DateTime synchDateTime;

        private static DateTime tickStartTime;

        private static DateTime tockEndTime;

        private static TimeSpan timeDiff;

        private static long elapsedMilliseconds;

        private static object utilLock = new object();

        private static StringBuilder sb = new StringBuilder(256);

        public static void synchTime(int year, int month, int day, int hour, int minute, int second)
        {
            synchDateTime = new DateTime(year, month, day, hour, minute, second);

            lock (utilLock) { Program.MessageQueue.Enqueue(Logger.getNewLogArrayHeader(UTF8Encoding.UTF8.GetBytes("Before synchTime DateTime.Now = " + DateTime.Now.ToString()))); }
            lock (utilLock) { Program.MessageQueue.Enqueue(Logger.getNewLogArrayHeader(UTF8Encoding.UTF8.GetBytes("Before synchTime RTC.Now = " + RealTimeClock.GetTime().ToString()))); }
 
            Utility.SetLocalTime(synchDateTime);    //Set .Net DateTime
            RealTimeClock.SetTime(synchDateTime);   //Set RTC to .Net DateTime

            lock (utilLock) { Program.MessageQueue.Enqueue(Logger.getNewLogArrayHeader(UTF8Encoding.UTF8.GetBytes("After synchTime DateTime.Now = " + DateTime.Now.ToString()))); }
            lock (utilLock) { Program.MessageQueue.Enqueue(Logger.getNewLogArrayHeader(UTF8Encoding.UTF8.GetBytes("After synchTime RTC.Now = " + RealTimeClock.GetTime().ToString()))); }
            Program.timeSynched = true;
        }

        public static void tick()
        {
            tickStartTime = DateTime.Now;
        }

        public static void tock()
        {
            tockEndTime = DateTime.Now;

            timeDiff = tockEndTime - tickStartTime;
            elapsedMilliseconds = (timeDiff.Days * 24 * 3600 * 1000) + (timeDiff.Hours * 3600 * 1000) + (timeDiff.Seconds * 1000) + timeDiff.Milliseconds;

            sb.Clear();
            sb.Append("Elapsed time (mSec) = ");
            sb.Append(elapsedMilliseconds.ToString());
            Debug.Print(sb.ToString());
        }
    }
}
