#include "common.h"
#include "menu.h"
#include "buttons.h"
#include "screen.h"
#include "games.h"
#include "wifictrl.h"

typedef enum
{
  MAIN_STATE_MENU = (0),
  MAIN_STATE_SETTINGS,
  MAIN_STATE_GAMES,
  MAIN_STATE_MAX,
} MainState_e;

static MainState_e _mainstate = MAIN_STATE_MENU;
static Menu_st _mainmenu;

void setup()
{
  /* Serial */
  Serial.begin(115200);
  // delay(3000);              //Delay for Serial Monitor startup

  /* Screen */
  if (!SCREEN_Init()) {
    while (1) {
      #if defined(LED_BUILTIN)
        pinMode(LED_BUILTIN, OUTPUT);
        digitalWrite(LED_BUILTIN, LOW);
        delay(200);
        digitalWrite(LED_BUILTIN, HIGH);
        delay(200);
      #else
        delay(10);
      #endif
    }
  }
  delay(GAME_START_SCREEN_TIME);

  /* Database */
  DB_Init();

  /* Games */
  GAMES_Init();

  /* Buttons */
#if defined(KEYS_CONTROL_BUTTONS)
  BUTTONS_Init();
#endif

  /* Joystick */
#if defined(KEYS_CONTROL_JOYSTICK)
  JOYSTICK_Init();
#endif

  /* WiFi */
#if defined(KEYS_CONTROL_WIFI)
  WIFI_Init();
#endif

  /* MENU */
  MAINMENU_Init(&_mainmenu, GAMES_GetTotalGamesNum(), GAMES_GetGameName);
  MAINMENU_DrawPage(&_mainmenu, "MAIN MENU");
}

void loop()
{
  int8_t gameindex = 0;

  switch (_mainstate)
  {
    case MAIN_STATE_MENU:
      gameindex = MAINMENU_Task(&_mainmenu);
      if (gameindex >= 0)
      {
        _mainstate = MAIN_STATE_GAMES;
        GAMES_Start(gameindex);

        _mainstate = MAIN_STATE_MENU;
        MAINMENU_DrawPage(&_mainmenu, "MAIN MENU");
      }
      break;

    case MAIN_STATE_GAMES:

      break;

    default:

      break;
  }

  WOKWI_DELAY
}