#pragma once

extern Player melody;

bool timeToStop(unsigned long now);
bool timeToPause(unsigned long now);
bool timeToResume(unsigned long now);
void durationTimer(void *param);

// Timer TASK to control playback state
void durationTimer(void *param) {

  // Task Setup

  // Task Loop
  while (true) {

    unsigned long now = millis();

    if (timeToStop(now)) {
        player.stop();
    } else if (timeToPause(now)) {
        player.pause();
    } else if (timeToResume(now)) {
        player.unpause();
    }

    vTaskDelay(pdMS_TO_TICKS(500)); // Check every 500ms
    }
}

// Check if it's time to stop playback
bool timeToStop(unsigned long now) {
    if (player.isPlaying && !player.infinite_play) {
        uint64_t stopTime = player.startTime + player.total_duration;
        if (now >= stopTime) {
            LOG_DEBUG("(TimerFunction) Total Run Duration Reached. Soft Stopping.");
            return true;
        }
    }
    return false;
}

// Check if it's time to pause playback
bool timeToPause(unsigned long now) {
    if (player.isPlaying && player.continuous_loop) {
        uint64_t timeToPause = player.segmentStartTime + player.segment_duration;
        LOG_DEBUG("PTL: %llu // NOW: %lu", timeToPause, now);
        if (now >= timeToPause && !player.isPaused) {
            LOG_DEBUG("(TimerFunction) Segment Duration Reached. Pausing.");
            player.pauseTime = now;
            return true;
        }
    }
    return false;
}

// Check if it's time to resume playback
bool timeToResume(unsigned long now) {
    if (player.isPaused) {
        uint64_t timeToResume = player.segmentCmpltTime + player.pause_duration;
        if (now >= timeToResume) {
            LOG_DEBUG("(TimerFunction) Pause Duration Reached. Resuming");
            return true;
        }
    }
    return false;
}
