/**
 * Copyright (c) 2021 Dominic Masters
 * 
 * This software is released under the MIT License.
 * https://opensource.org/licenses/MIT
 */

#include "menu.h"

void menuInit(menu_t *menu, int32_t columns, int32_t rows) {
  int32_t i;
  menu->columns = columns;
  menu->rows = rows;
  menu->holdAllow = true;
  menu->direction = 0x00;
  for(i = 0; i < MENU_ITEMS_MAX; i++) menu->items[i] = NULL;
}

void menuUpdate(menu_t *menu, engine_t *engine) {
  inputbind_t bind;
  float heldTime, heldDue;

  // Handle press binds.
  if(inputIsPressed(&engine->input, INPUT_DOWN)) {
    menu->y = (menu->y + 1) % menu->rows;
    menu->direction = MENU_DIRECTION_DOWN;
  } else if(inputIsPressed(&engine->input, INPUT_UP)) {
    menu->y = (menu->y - 1) % menu->rows;
    menu->direction = MENU_DIRECTION_DOWN;
  } else if(inputIsPressed(&engine->input, INPUT_LEFT)) {
    menu->x = (menu->x - 1) % menu->columns;
    menu->direction = MENU_DIRECTION_DOWN;
  } else if(inputIsPressed(&engine->input, INPUT_RIGHT)) {
    menu->x = (menu->x + 1) % menu->columns;
    menu->direction = MENU_DIRECTION_DOWN;
  }

  // Handle held
  if(menu->holdAllow && menu->direction != 0x00) {
    bind = (
      menu->direction == MENU_DIRECTION_DOWN ? INPUT_DOWN :
      menu->direction == MENU_DIRECTION_UP ? INPUT_UP :
      menu->direction == MENU_DIRECTION_LEFT ? INPUT_LEFT :
      menu->direction == MENU_DIRECTION_RIGHT ? INPUT_RIGHT :
      INPUT_NULL
    );

    if(inputIsDown(&engine->input, bind)) {
      heldTime = engine->time.current - inputGetAccuated(&engine->input, bind);
      heldDue = engine->time.current - menu->holdLast;
      
      // Have we held long enough?
      if(heldTime >= MENU_HOLD_DURATION) {
        
        menu->holdLast = engine->time.current;
      }
    } else {
      menu->holdLast = engine->time.current;
    }
  }

  // Handle Mouse

}