/*
 * Copyright © 2022 Codethink Ltd.
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice (including the
 * next paragraph) shall be included in all copies or substantial
 * portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include "ilm.h"
#include <ilm_control.h>
#include <stdlib.h>

void ilm_list_screens(char *reply) {}

qad_screen_buffer_t *ilm_grab_fb(int screen) {
  char filename[255];
  int ret;
  ilmErrorTypes error;
  qad_screen_buffer_t *buffer = calloc(1, sizeof(qad_screen_buffer_t));
  if (!ilm_isInitialized()) {
    error = ilm_init();
    if (error != ILM_SUCCESS) {
      fprintf(stderr, "Could not init ILM: %s\n", ILM_ERROR_STRING(error));
      return NULL;
    }
  }
  sprintf(filename, "/tmp/out_%d.bmp", screen);
  error = ilm_takeScreenshot(screen, filename);
  if (error != ILM_SUCCESS) {
    fprintf(stderr, "Could not take screenshot: %s\n", ILM_ERROR_STRING(error));
    return NULL;
  }

  FILE *file = fopen(filename, "r");
  if (!file) {
    return NULL;
  }

  fseek(file, 0, SEEK_END);
  buffer->buffer_size = ftell(file);
  rewind(file);

  buffer->buffer = (unsigned char *)malloc(buffer->buffer_size);
  ret = fread(buffer->buffer, 1, buffer->buffer_size, file);
  if (ret != buffer->buffer_size) {
    fprintf(stderr, "Failed to read file!\n");
    return NULL;
  }
  fclose(file);
  return buffer;
}

qad_backend_screen_t *ilm_create_backend() {
  qad_backend_screen_t *backend = calloc(1, sizeof(qad_backend_screen_t));
  backend->list_fbs = ilm_list_screens;
  backend->grab_fb = ilm_grab_fb;
  return backend;
}
