using UnityEngine;
using System.Collections;
using System;
public class ServerTime : MonoBehaviour
{
#region Unity Singleton
private static ServerTime _instance;
public static ServerTime Instance
{
get
{
if (_instance == null)
{
_instance = FindObjectOfType(typeof(ServerTime)) as ServerTime;
if (_instance == null)
{
AVDebug.LogError(string.Format("No gameObject with {0} component exists. Make sure to create a gameObject with {0} component", new System.Diagnostics.StackFrame().GetMethod().DeclaringType));
}
}
return _instance;
}
}
void Awake()
{
if (_instance != null && _instance != this)
{
AVDebug.LogWarning(string.Format("{0} Instance already exists on another gameObject. Destroying this gameObject {1}", this.GetType().Name, gameObject.name));
Destroy(gameObject);
return;
}
_instance = this;
DontDestroyOnLoad(gameObject);
}
#endregion
///
/// Returns the server time as a Unix Time Stamp, i.e. current time in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT),
/// through the onComplete action.
/// If there was an error, -1 is returned through the onComplete action
///
public void RetrieveServerTime(Action onComplete)
{
AVDebug.Assert(onComplete != null, "onComplete must not be null when requesting server time");
StartCoroutine(RetrieveServerTimeCoroutine(onComplete));
}
IEnumerator RetrieveServerTimeCoroutine(Action onComplete)
{
WWW www = new WWW(GameConstants.SERVER_BASE_URL + "serverTime.php");
yield return www;
if (www.error != null)
{
onComplete(-1);
} else
{
long serverTime;
if (long.TryParse(www.text, out serverTime))
{
onComplete(serverTime);
} else
{
onComplete(-1); //parse error
}
}
}
}