/*
 * remote_control.c
 * Code related to the local control mode
 *
 *  Created on: Nov 4, 2025
 *      Author: sowgro
 */

#include <stm32l4xx.h>
#include <stdio.h>
#include <string.h>
#include "player_actions.h"
#include "UART.h"
#include "project.h"
#include "systick.h"
#include "player_actions.h"

static char buffer[80];
static char* cur = buffer;

void parse_input(char buffer[]);

/**
 * Initialize remote control mode (does not enable it)
 */
void remote_control_init() {
    NVIC_EnableIRQ (USART2_IRQn);
    USART2->CR1 |= USART_CR1_RXNEIE; // 1 << 5

	player_help();
}

/**
 * Logic that should be called constantly from the main loop.
 */
void remote_control_loop() {
	if (*cur == '\r') {
		*cur = 0;
		parse_input(buffer);
		cur = buffer;
	}
}

/**
 * Parses the input string and calls the correct command
 * @param buffer a null terminated string of the input
 */
void parse_input(char buffer[]) {
	if (!strcmp(buffer, "HELP")) {
		player_help();
	}
	else if (!strcmp(buffer, "NEXT")) {
		player_next();
	}
	else if (!strcmp(buffer, "PLAY")) {
		player_play();
	}
	else if (!strcmp(buffer, "PAUSE")) {
		player_pause();
	}
	else if (!strcmp(buffer, "STOP")) {
		player_stop();
	}
	else {
		printf("Unknown command \"%s\"\n\r", buffer);
	}
}

/**
 * Handles user input
 */
void USART2_IRQHandler() {
	int ch = USART_Read(USART2);

	if (project_get_mode() != REMOTE_MODE) {
		cur = buffer;
		return;
	}

	putchar(ch);
	if (!ch)
		return;

	if (ch == '\r') {
		putchar('\n');
		*cur = ch;
		return;
	}

	if (ch == 0x08 || ch == 0x7F) { // backspace
		if (cur <= buffer)
			return;
		cur--;
		printf("\b \b");
		return;
	}

	*cur++ = ch;
}


