/*
 *  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/>.
 */

#ifdef MAGICKWAND7
#include <MagickWand/MagickWand.h>
#else
#include <wand/magick_wand.h>
#endif
#include "image_8bits.h"


int
Image8_load_any(Image8_t *img, const char *file)
{
  MagickWand *wand = NULL;
  MagickBooleanType status;
  int res = -1;

  wand = NewMagickWand();
  if (NULL != wand) {
    status = MagickReadImage(wand, file);
    if (status == MagickTrue) {
#ifdef MAGICKWAND7
      status = MagickResizeImage(wand, WIDTH, HEIGHT, LanczosFilter);
#else
      status = MagickResizeImage(wand, WIDTH, HEIGHT, LanczosFilter, 1);
#endif
      if (status == MagickTrue) {
        status = MagickFlipImage(wand);
        if (status == MagickTrue) {
          status = MagickExportImagePixels(wand, 0, 0, WIDTH, HEIGHT, "I", CharPixel, (void *)img->buff->buffer);
          if (status == MagickTrue) {
            res = 0;
          }
        }
      }
    }
    DestroyMagickWand(wand);
  }

  return res;
}


int
Image8_load(Image8_t *img, const uint32_t id, const char *dir, const char *filename)
{
  gchar *file = g_strdup_printf("%s/%s", dir, filename);

  if (Image8_load_any(img, file) != 0) {
    g_free(file);
    return -1;
  }
  g_free(file);

  xfree(img->name);
  img->name = strdup(filename);
  xfree(img->dname);
  img->dname = strdup(img->name);

  if (NULL != (file = strchr(img->dname, '.'))) {
    *file = '\0';  /* spr0tch */
  }

  img->id = id;

  return 0;
}


void
Image8_to_PNG(const Image8_t *img, uint8_t **data, uint32_t *datalen)
{
  MagickWand *wand = NULL;

  *data = NULL;
  *datalen = 0;
  wand = NewMagickWand();
  if (NULL != wand) {
    MagickBooleanType status;

    status = MagickConstituteImage(wand, WIDTH, HEIGHT, "I", CharPixel, img->buff->buffer);
    if (status == MagickTrue) {
      status = MagickFlipImage(wand);
      if (status == MagickTrue) {
        status = MagickSetImageFormat(wand, "PNG");
        if (status == MagickTrue) {
          size_t png_datalen;
          uint8_t *png_data = MagickGetImageBlob(wand, &png_datalen);

          *datalen = png_datalen;
          *data = xmalloc(png_datalen * sizeof(uint8_t));
          memcpy(*data, png_data, png_datalen * sizeof(uint8_t));
          MagickRelinquishMemory(png_data);
        }
      }
    }
    DestroyMagickWand(wand);
  }
}
