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

public class SliderAnim : MonoBehaviour {

    public Slider loadingSlider;

    public Text loadingProgressText;

    // Use this for initialization
    void Start () {
		
	}

    public void ResetAnim()
    {
        SetSliderValue(0);
    }

    private Action m_OnEnd;
    public void PlaySlider(float time,Action onEnd)
    {
        m_OnEnd = onEnd;
        
        Invoke("CallBack",time);

        this.gameObject.SetActive(true);
        StartCoroutine(PlaySlider(time));
    }

    void CallBack()
    {
        m_OnEnd?.Invoke();
    }
    
    public IEnumerator PlaySlider(float time)
    {
        float initValue = loadingSlider.value;

        float timer = 0;
        while (timer < time)
        {
            timer += Time.deltaTime;
            float rate = timer / time;
            float value = Mathf.Lerp(initValue, 1, rate);

            SetSliderValue(value);

            yield return null;
        }

    }

    public void SetSliderValue(float value)
    {
        value = value < 0.07f ? 0.07f : value;
        if (loadingSlider)
            loadingSlider.value = value;

        if (loadingProgressText)
            loadingProgressText.text = string.Format("{0:P1}", value);
    }

    private void OnDestroy()
    {
        m_OnEnd = null;
    }

    // Update is called once per frame
    void Update () {
		
	}
}
