using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Clock : MonoBehaviour {

    public static Clock instance;

    public Transform needle;

    IEnumerator countDownRoutine;
    
    private void Awake ()
    {
        if (instance == null)
        {
            instance = this;
        }
        else
        {
            Destroy(this);
        }
    }

    public void SetCountDown (float time)
    {
        if (countDownRoutine != null)
        {
            StopCoroutine(countDownRoutine);
            countDownRoutine = null;
        }
        countDownRoutine = runCountDown(time);
        StartCoroutine(countDownRoutine);
    }

    IEnumerator runCountDown (float totalTime)
    {
        float startTime = Time.time;
        float timeElapsed = Time.time - startTime;
        while (timeElapsed < totalTime)
        {
            setNeedleRotation(360 * ( timeElapsed / totalTime ));
            timeElapsed = Time.time - startTime;
            yield return null;
        }
        //SFX Timer done
    }

    public void setNeedleRotation (float y)
    {
        needle.localRotation = Quaternion.Euler(0, -y, 0);
    }

    public void Clear ()
    {
        if (countDownRoutine != null)
        {
            StopCoroutine(countDownRoutine);
            countDownRoutine = null;
        }
        setNeedleRotation(0);
    }
}
