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

public class TimerScript : MonoBehaviour
{
    Image circleImage;
    Color circleColor;
    public Text timerText;
    float time;
    float timeAmount;

    public bool mainTimer;

    bool timerRunning = false;

    Color finalColor = new Color32(130,0,16,220);
    Color startlColor = new Color32(16, 0, 255, 200);

    GameManagerScript gms;
    TimerScript dialogTimer;

    // Start is called before the first frame update
    void Start()
    {
        dialogTimer = GameObject.Find("DialogTimerCircle").GetComponent<TimerScript>();
        gms = GameObject.Find("GameManager").GetComponent<GameManagerScript>();
        circleImage = this.GetComponent<Image>();
        
        circleColor = circleImage.color;

        timerText.text = time.ToString("F0");
    }
    public void StopTimer() {
        timerRunning = false;
        dialogTimer.timerRunning = false;
    }

    public void ResetTimer() {
        time = gms.QuestionTimer;
        // time = Database.Instance.GetQuestionTimer(gms.GameId, gms.GameMode);
        timeAmount = time;
        circleColor = Color.Lerp(startlColor, finalColor, 1 - (time / timeAmount));

        dialogTimer.time = time;
        dialogTimer.timeAmount = timeAmount;
        dialogTimer.circleImage.color = circleColor;
        dialogTimer.timerText.text = time.ToString("F0");

        circleImage.color = circleColor;
        timerText.text = time.ToString("F0");
    }

    // Update is called once per frame
    void Update()
    {
        if (timerRunning) {
            circleColor = circleImage.color;
            if (time > 0) {
                time -= Time.deltaTime;
                circleColor = Color.Lerp(startlColor, finalColor, 1 - (time / timeAmount));

                circleImage.color = circleColor;
                timerText.text = time.ToString("F0");
            } else {
                timerRunning = false;

                // send message to fail question
                if (mainTimer) {
                    EventManager.TriggerEvent("TimerEvent");
                }
            }
        }
    }

    internal void StartTimer() {
        timerRunning = true;
        dialogTimer.timerRunning = true;
    }
}
