/*
 *  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 "context.h"

#define DIRECTORY      "/screenshots/"


static gchar *
screenshot_filename(void)
{
  gchar *filename = NULL;
  time_t s;
  struct tm *now;

  s = time(NULL);
  now = localtime(&s);
  filename = g_strdup_printf("%s/." PACKAGE_NAME DIRECTORY, g_get_home_dir());
  g_mkdir_with_parents(filename, DIRECTORY_MODE);
  g_free(filename);

  filename = g_strdup_printf("%s/." PACKAGE_NAME DIRECTORY PACKAGE_NAME "-%04d-%02d-%02d_%02d-%02d-%02d.png",
                             g_get_home_dir(), now->tm_year + 1900, now->tm_mon + 1, now->tm_mday,
                             now->tm_hour, now->tm_min, now->tm_sec);

  return filename;
}


void
Context_screenshot(Context_t *ctx, const u_char frame_number_mode)
{
  gchar *filename = NULL;

  if (frame_number_mode) {
    extern uint64_t frames;
    char *video_filename = getenv("LEBINIOU_MP4_FILENAME");
    if (NULL == video_filename) {
      xerror("%s: frame_number_mode set but no encoding in progress ?\n", __func__);
    }
    filename = g_strdup_printf("%s-%06"PRIu64".png", video_filename, frames);
  } else {
    filename = screenshot_filename();
  }
  FILE* fp = fopen(filename, "wb");

  if (NULL == fp) {
    xperror("fopen");
  } else {
    uint8_t *png = NULL;
    size_t png_datalen;
    size_t result;

    Context_to_PNG(ctx, &png, &png_datalen, WIDTH, HEIGHT);
    result = fwrite(png, sizeof(uint8_t), png_datalen, fp);
    MagickRelinquishMemory(png);
    if (result != png_datalen) {
      xerror("Failed to save screenshot %s\n", filename);
    }
    if (fclose(fp) != 0) {
      xperror("fclose");
    }
    if (!frame_number_mode) {
      VERBOSE(printf("[i] %s: saved screenshot to %s\n", __FILE__, filename));
    }
    g_free(filename);
  }
}
