using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GetHttpTimer : MonoSingleton<GetHttpTimer>
{

    public long timestamp = -1;

    private float nowTimes = 0;

    private void Start()
    {
        StartCoroutine(HttpTool.Instance.SendHttp(HttpEdustryAction.timestamp, "", (string msg) =>
        {
            Debug.Log(msg);
            JObject data = JObject.Parse(msg);
            if (data["code"].ToString() == "200")
            {
                timestamp = long.Parse(data["data"]["timestamp"].ToString());
                nowTimes = 0;

                Debug.Log(timestamp);
            }
            else
            {
                Debug.LogError(HttpEdustryAction.timestamp + "  Error   " + data["code"].ToString());
            }

        }));
    }
    void Update()
    {
        if (timestamp !=-1)
        {
            nowTimes += Time.deltaTime;

           // timestamp += Convert.ToInt64(Time.deltaTime);
        }
    }

    public DateTime GetTimer()
    {
        if (timestamp == -1)
            return System.DateTime.Now;

        return UnixTimeStampToDateTime((timestamp+(long)nowTimes));
    }

    // ��Unixʱ���ת��ΪDateTime
    DateTime UnixTimeStampToDateTime(long unixTimeStamp)
    {

      //  string times = unixTimeStamp.ToString() + "000";

      //  long timestamp = long.Parse(times);
        // Unix��ʼʱ��
      //  DateTime unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.);


        DateTime startTime = System.TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));//��ȡʱ���
        DateTime dt = startTime.AddSeconds(unixTimeStamp);
        // ��ʱ���ת��ΪDateTime
        return dt;


        
      
    }

    /// <summary>    
    /// ʱ���תΪC#��ʽʱ��    
    /// </summary>    
    /// <param name=��timeStamp��></param>    
    /// <returns></returns>    
    public static DateTime ConvertStringToDateTime(string timeStamp)
    {
        DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
        long lTime = long.Parse(timeStamp + "0000");
        TimeSpan toNow = new TimeSpan(lTime);
        return dtStart.Add(toNow);
    }
}