#include "pam.h"
#include "img.h"
#include "mem_arena.h"
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>

void write_p7_image(u64 width, u64 height, u8 *buf, const char *outfile) {
  FILE *fp = fopen(outfile, "wb");
  if (!fp) {
    fprintf(stderr, "Couldn't open file: %s\n", outfile);
    return;
  }

  char header[4096] = {0};
  snprintf(header, 4095,
           "P7\n"
           "WIDTH %lu\n"
           "HEIGHT %lu\n"
           "DEPTH 4\n"
           "MAXVAL 255\n"
           "TUPLTYPE RGB_ALPHA\n"
           "ENDHDR\n",
           width, height);

  u64 hdr_size = strlen(header);
  u64 buf_size = width * height * 4;

  fwrite(header, hdr_size, 1, fp);
  fwrite(buf, buf_size, 1, fp);

  fclose(fp);
}

Image *load_p6_image(Arena *arena, const char *filename) {
  Image *output = NULL;

  if (!arena || !filename) {
    goto RETURN_VALUE;
  }

  FILE *fp = fopen(filename, "rb");
  if (!fp) {
    goto RETURN_VALUE;
  }

  char type[4] = {0};
  fread(type, 3, 1, fp);
  if (strncmp(type, "P6\n", 4) != 0) {
    goto CLOSE_FILE;
  }

  u64 w, h;
  fscanf(fp, "%lu %lu\n", &w, &h);

  u64 max;
  fscanf(fp, "%lu\n", &max);
  if (max > UINT8_MAX) {
    goto CLOSE_FILE;
  }

  output = wapp_mem_arena_alloc(arena, sizeof(Image));
  if (!output) {
    goto CLOSE_FILE;
  }

  output->width = w;
  output->height = h;
  if (!init_buffer(arena, output)) {
    goto CLOSE_FILE;
  }

  Colour colour = {0};
  for (u64 y = 0; y < h; ++y) {
    for (u64 x = 0; x < w; ++x) {
      fread(&colour, 3, 1, fp);
      colour.a = 255;
      set_pixel(output, x, y, &colour);
    }
  }

CLOSE_FILE:
  fclose(fp);

RETURN_VALUE:
  return output;
}
