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

#include "textmenu.h"

void _textMenuOnSelect(void *user, uint8_t i) {
  textmenu_t *textMenu = (textmenu_t *)user;

  if(textMenu->onSelect != NULL) {
    textMenu->onSelect(textMenu->user, i, textMenu->texts[i]);
  }
}

void textMenuInit(textmenu_t *menu, font_t *font) {
  menuInit(&menu->menu);
  gridInit(&menu->grid);
  rectangleInit(&menu->rectangle);
  rectangleSetColor(&menu->rectangle, TEXTMENU_SELECTION_COLOR);

  menu->menu.user = menu;
  menu->menu.onSelect = &_textMenuOnSelect;
  menu->font = font;
  menu->onSelect = NULL;
}

menuitem_t * textMenuAdd(textmenu_t *menu, char *item) {
  menu->texts[menu->menu.itemCount] = item;
  labelInit(menu->labels + menu->menu.itemCount);
  labelSetText(menu->labels + menu->menu.itemCount, menu->font, item);
  (menu->labels + menu->menu.itemCount)->font = menu->font;
  return menuAdd(&menu->menu);
}

void textMenuRender(textmenu_t *menu, shader_t *shader, float x, float y) {
  uint8_t i;
  label_t *label;
  menuitem_t *item;
  align_t align;
  float gx, gy;

  // Render selection box.
  item = menu->menu.items + menu->menu.selected;
  gridGetChild(
    &menu->grid, item->x, item->y, item->width, item->height,
    &gx, &gy, &menu->rectangle.width, &menu->rectangle.height
  );
  rectangleRender(&menu->rectangle, shader, x + gx, y + gy);

  // Render labels
  for(i = 0; i < menu->menu.itemCount; i++) {
    item = menu->menu.items + i;
    label = menu->labels + i;
    align = gridGetAndAlignChild(
      &menu->grid, item->x, item->y, item->width, item->height,
      ALIGN_POS_START | ALIGN_SIZE_ORIGINAL,
      ALIGN_POS_START | ALIGN_SIZE_ORIGINAL,
      label->info.width, label->info.height
    );
    labelRender(label, shader, align.x + x, align.y + y);
  }
}

void textMenuDispse(textmenu_t *menu) {
  uint8_t i;
  rectangleDispose(&menu->rectangle);
  for(i = 0; i < menu->menu.itemCount; i++) {
    labelDispose(menu->labels + i);
  }
}