using DotNet4.Utilities;
using ryCommon;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;

namespace TimeClock.API
{
   public class TimeSync
    {
        [StructLayoutAttribute(LayoutKind.Sequential)]
        public struct SystemTime
        {
            public short year;
            public short month;
            public short dayOfWeek;
            public short day;
            public short hour;
            public short minute;
            public short second;
            public short milliseconds;
        }
        /// <summary>
        /// 设置系统时间
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        [DllImport("kernel32.dll")]
        private static extern bool SetLocalTime(ref SystemTime time);

        public static bool SetDate(DateTime dt)
        {
            SystemTime systemtime;
            systemtime.year = (short)dt.Year;
            systemtime.month = (short)dt.Month;
            systemtime.dayOfWeek = (short)dt.DayOfWeek;
            systemtime.day = (short)dt.Day;
            systemtime.hour = (short)dt.Hour;
            systemtime.minute = (short)dt.Minute;
            systemtime.second = (short)dt.Second;
            systemtime.milliseconds = (short)dt.Millisecond;
            return SetLocalTime(ref systemtime);
        }

        public static DateTime ConvertIntDatetime(long utc)
        {
            return TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)).AddMilliseconds((double)utc);
        }
        public static void Sync()
        {
            var trycount = 0;
        retry1:
            try
            {
                string ntpserver = "time.windows.com";
                RyLine.NTPClient client = new RyLine.NTPClient(ntpserver);
                client.Connect(true); //参数为false时只从服务器获取信息，为true时同时自动更新本机时间
            }
            catch (Exception ex)
            {
                trycount++;
                if (trycount <= 1)
                {
                    goto retry1;
                }
            }
        }
    }
}
