﻿using UnityEngine;
using UnityEngine.UI;
using System.Collections;

namespace Nostalgia.Example
{
	[AddComponentMenu("Nostalgia/Example/Timer")]
	public sealed class Timer : MonoBehaviour
	{
		[SerializeField] private Text _SecText = null;
		[SerializeField] private Text _MilliSecText = null;
		[SerializeField] private GameObject _NewRecort = null;

		private float _Timer = 0.0f;
		public float timer
		{
			get
			{
				return _Timer;
			}
		}
		private bool _IsUpdate = true;

		private bool _IsInitializeTexts = false;
		private int _SecCache = 0;
		private int _MilliSecCache = 0;

		private static readonly string _RecordTimePrefsKey = "RecordTime";

		public void OnGoal()
		{
			_IsUpdate = false;

			if (!PlayerPrefs.HasKey(_RecordTimePrefsKey) || PlayerPrefs.GetFloat(_RecordTimePrefsKey) > _Timer)
			{
				PlayerPrefs.SetFloat(_RecordTimePrefsKey, _Timer);
				_NewRecort.SetActive(true);
			}
		}

		void Update()
		{
			if (!_IsUpdate)
			{
				return;
			}

			_Timer += Time.deltaTime;

			int sec = Mathf.FloorToInt(_Timer);
			int milliSec = Mathf.FloorToInt((_Timer - sec) * 1000.0f);

			if (!_IsInitializeTexts || sec != _SecCache)
			{
				_SecText.text = sec.ToString();
				_SecCache = sec;
			}

			if (!_IsInitializeTexts || milliSec != _MilliSecCache)
			{
				_MilliSecText.text = milliSec.ToString("000");
				_MilliSecCache = milliSec;
			}

			_IsInitializeTexts = true;
		}
	}
}
