using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UIElements;

using UITypes;

public class Game : MonoBehaviour
{
	const float DELAY = 0.005f; // 200 TPS

	public AudioManager manager;

	private MainMenu menu;
	private BassEffect effect;

	string totalDuration;
	bool repeatRoutine = true;


	void Awake()
	{
		menu = GetComponent<MainMenu>();

		effect = new(manager.source);
	}

	public void GameUpdate()
	{
		float[] specData = effect.UpdateSpectrumData();
		float bassStrength = effect.GetBassStrength();

		menu.GameElem.UpdateVisualizers(specData, bassStrength);

		UpdateTimestamp();
	}

	IEnumerator GameLoop()
	{
		while (repeatRoutine)
		{
			GameUpdate();
			yield return new WaitForSeconds(DELAY);
		}
	}

	public void LoadSong(SongEntry song)
	{
		totalDuration = song.Song.Duration;

		manager.source.clip = song.Song.Clip;

		menu.GameElem.SetColumnColor(song.Song.AverageColor);
	}

	void UpdateTimestamp()
	{
		int totalSeconds = (int)manager.source.time;
		int h = totalSeconds / 3600;
		int m = (totalSeconds % 3600) / 60;
		int s = totalSeconds % 60;

		string result = $"{h:D2}:{m:D2}:{s:D2} / {totalDuration}";
		menu.GameElem.UpdateSongTime(result);
	}

	public void EscapeClicked()
	{
		repeatRoutine = false;
		manager.Stop();
		menu.Escape();
	}

	public void Play()
	{
		manager.Play();
		repeatRoutine = true;
		StartCoroutine(GameLoop());
	}
}
