#include "df_player.hpp"

void DfPlayer::SendCommand(Command cmd, uint16_t param) {
    uint8_t buffer[10];
    buffer[0] = kStartByte;
    buffer[1] = kVersion;
    buffer[2] = 0x06;
    buffer[3] = static_cast<uint8_t>(cmd);
    buffer[4] = kFeedback;
    buffer[5] = (param >> 8) & 0xFF;
    buffer[6] = param & 0xFF;

    uint16_t checksum = 0xFFFF - (kVersion + 0x06 + static_cast<uint8_t>(cmd) + kFeedback + buffer[5] + buffer[6]) + 1;
    buffer[7]         = (checksum >> 8) & 0xFF;
    buffer[8]         = checksum & 0xFF;
    buffer[9]         = kEndByte;

    serialPort->WriteBytesBlocking(buffer, sizeof(buffer));
}

void DfPlayer::Play() {
    SendCommand(Command::kPlay);
}

void DfPlayer::Stop() {
    SendCommand(Command::kStop);
}

void DfPlayer::SetVolume(uint8_t volume) {
    if (volume > 30) {
        volume = 30;
    }
    SendCommand(Command::kSetVolume, volume);
}

void DfPlayer::PlayTrack(uint16_t track) {
    if (track < 1 || track > 2999) {
        return;
    }
    SendCommand(Command::kPlayTrack, track);
}
