/*
 *  Copyright 1994-2022 Olivier Girondel
 *
 *  This file is part of lebiniou.
 *
 *  lebiniou is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  lebiniou is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with lebiniou. If not, see <http://www.gnu.org/licenses/>.
 */

#include <inttypes.h>
#include "images.h"
#include "brandom.h"


uint32_t
Images_random_id(void)
{
  uint16_t idx = 0;

  assert(NULL != images);
  assert(images->size); // There is at least a default image

  if (images->size > 1) {
    idx = b_rand_uint32_range(0, images->size - 1);
  }

  return images->imgs[idx]->id;
}


uint32_t
Images_find(const char *name)
{
  uint16_t i;

  if (NULL == images) {
    fprintf(stderr, "[!] No images loaded\n");
    return 0;
  }

  for (i = 0; i < images->size; i++)
    if (is_equal(images->imgs[i]->name, name)) {
      return images->imgs[i]->id;
    }

  VERBOSE(fprintf(stderr, "[!] Image '%s' not found\n", name));

  return images->imgs[0]->id; /* Use the first image by default */
}


int32_t
Images_index(const uint32_t id)
{
  uint16_t i;

  if (NULL == images) {
    fprintf(stderr, "[!] No images loaded\n");
    return -1;
  }

  for (i = 0; i < images->size; i++)
    if (images->imgs[i]->id == id) {
      return i;
    }

  VERBOSE(fprintf(stderr, "[!] Images_index: id %"PRIu32" not found\n", id));

  return 0; /* Use the first image by default */
}


const char *
Images_name(const uint32_t id)
{
  uint16_t i;

  if (NULL == images) {
    VERBOSE(fprintf(stderr, "[!] No images loaded\n"));
    return NULL;
  }

  for (i = 0; i < images->size; i++)
    if (images->imgs[i]->id == id) {
      return images->imgs[i]->name;
    }

  if (id == 0) {
    return images->imgs[0]->name;
  }

  VERBOSE(fprintf(stderr, "[!] Images_name: id %"PRIu32" not found\n", id));

  return NULL;
}


const Image8_t *
Images_random(void)
{
  uint16_t idx = 0;

  assert(NULL != images);

  if (images->size > 1) {
    idx = b_rand_uint32_range(0, images->size - 1);
  }

  return images->imgs[idx];
}
