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

[RequireComponent(typeof(AudioSource))]
public class PlayEngine : SingletonBehaviour<PlayEngine>
{
    public LevelListscriptableObject levelList;
    public ForwardNoteObject ForwardNoteObject;
    public EdgeNoteObject[] EdgeNoteObjects = new EdgeNoteObject[4];
    private double startTime;

    private Level level;

    private AudioSource audioSource;
    private AudioClip audioClip;

    private bool isPlaying;
    private double startDspTime;

    public int test;
    public void Start()
    {
        audioSource = GetComponent<AudioSource>();
        LoadAndPlay(0);
    }
    public void LoadAndPlay(int idx)
    {
        var levelData = levelList.levels[idx];
        var bmsText = levelData.bms.text;
        var audioFile = levelData.audioFile;
        var offsetBarTime = levelData.offsetBarTime;

        var bms = new BmsParser().Parse(bmsText);
        var level = bms.ToLevel();

        this.level = level;

        var dspTime = AudioSettings.dspTime;
        var scheduleOffset = 0.5; // scheduling offset
        var playOffset = scheduleOffset + offsetBarTime * (60.0 / level.bpm) * 4; // includes offset bar time

        startDspTime = scheduleOffset + dspTime;

        audioSource.clip = audioFile;
        audioSource.PlayScheduled(playOffset + dspTime);
        Debug.Log(playOffset);
    }

    private void Update()
    {
        if (level != null)
        {
            var time = AudioSettings.dspTime - startDspTime;
            level.UpdateNotes(time);
        }

        if (Input.GetKeyDown(KeyCode.LeftArrow))
        {
            audioSource.time -= 1.0f;
        }

        if (Input.GetKeyDown(KeyCode.RightArrow))
        {
            audioSource.time += 1.0f;
        }
    }
}
