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

#include "../utils/common.h"
#include "../utils/file.h"
#include "../utils/image.h"

#define RESIZE_VARIANT_COUNT 4
int RESIZE_SCALES[RESIZE_VARIANT_COUNT] = { 1, 2, 3, 4 };

int main(int argc, char *argv[]) {
  FILE *file;
  char path[FILENAME_MAX + 1];
  char xml[2048];
  char *in;
  char *out;
  int w, h, channels, rw, rh, i, scale;
  stbi_uc *dataOriginal;
  stbi_uc *dataResized;

  if(argc != 3) {
    printf("Invalid number of arguments\n");
    return 1;
  }

  // Set up strings
  in = argv[1];
  out = argv[2];
  
  // Normalize slashes
  fileNormalizeSlashes(in);
  fileNormalizeSlashes(out);
  
  // Check the output doesn't already exist
  sprintf(path, "%s.xml", out);
  file = fopen(path, "rb");
  if(file != NULL) {
    fclose(file);
    return 0;
  }

  // Read in original texture
  file = fopen(in, "rb");
  if(file == NULL) {
    printf("Failed to open file!\n");
    return 1;
  }

  dataOriginal = stbi_load_from_file(file, &w, &h, &channels, STBI_rgb_alpha);
  if(dataOriginal == NULL) {
    printf("Failed to load input texture!\n");
    return 1;
  }
  fclose(file);

  // Begin XML buffering
  xml[0] = '\0';
  sprintf(xml,
    "<texture channels=\"%i\" width=\"%i\" height=\"%i\">",
    STBI_rgb_alpha, w, h
  );

  // For each scale.
  for(i = 0; i < RESIZE_VARIANT_COUNT; i++) {
    // Resize image
    scale = RESIZE_SCALES[i];
    rw = w / scale;
    rh = h / scale;
    dataResized = malloc(sizeof(stbi_uc) * rw * rh * STBI_rgb_alpha);
    stbir_resize_uint8(
      dataOriginal, w, h, 0,
      dataResized, rw, rh, 0,
      STBI_rgb_alpha
    );

    // Determine output path
    sprintf(path, "%s_%i.texture", out, scale);

    // Open output file
    fileMkdirp(path);
    printf("OPOut %s\n", path);

    file = fopen(path, "wb");
    if(file == NULL) {
      printf("Invalid texture file out!\n");
      return 1;
    }

    // Write texture
    fwrite(dataResized, sizeof(unsigned char), rw * rh * STBI_rgb_alpha, file);

    // Cleanup
    fclose(file);
    free(dataResized);

    // Buffer XML info.
    sprintf(xml,
      "%s\n  <texture-scale scale=\"%i\" width=\"%i\" height=\"%i\" />",
      xml, scale, rw, rh
    );
  }

  // Cleanup
  stbi_image_free(dataOriginal);

  // Finalize XML
  sprintf(xml, "%s\n</texture>", xml);
  
  // Determine XML path
  sprintf(path, "%s.xml", out);

  // Write XML
  fileMkdirp(path);
  file = fopen(path, "w");
  if(file == NULL) {
    printf("Invalid XML File Out!\n");
    return 1;
  }
  fwrite(xml, sizeof(char), strlen(xml), file);
  fclose(file);

  return 0;
}