#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "backend.h"
#include "image.h"

// Write BMP file from image buffer
int encode_bmp(unsigned char *data, int width, int height, int stride,
               qad_screen_buffer_t *screen_buffer) {
  struct BMPHeader header;

  // Save data as BMP file
  header.type = 0x4D42;
  header.size = sizeof(struct BMPHeader) + stride * height;
  header.reserved1 = 0;
  header.reserved2 = 0;
  header.offset = sizeof(struct BMPHeader);
  header.header_size = sizeof(struct BMPHeader) - 14;
  header.width = width;
  header.height = height;
  header.planes = 1;
  header.bpp = 32; // 32 bits per pixel (RGBA)
  header.compression = 0;
  header.image_size = stride * height;
  header.x_resolution = 0;
  header.y_resolution = 0;
  header.colors = 0;
  header.important_colors = 0;

  screen_buffer->buffer = malloc(sizeof(struct BMPHeader) + header.image_size);
  if (screen_buffer->buffer == NULL) {
    fprintf(stderr, "Failed to allocate memory for screen buffer");
    return -1;
  }
  screen_buffer->buffer_size = sizeof(struct BMPHeader) + header.image_size;
  screen_buffer->type = BUFFER_TYPE_BMP;
  unsigned char *out = screen_buffer->buffer;
  memcpy(out, &header, sizeof(struct BMPHeader));
  out += sizeof(struct BMPHeader);
  // Write data to image
  memcpy(out, data, header.image_size);
  free(data);
  return 0;
}
