/* image-cairo.c
 * This file is part of Amsam photo cropping program
 * Copyright 2021, 2023, 2024, 2025, 2026 Nandakumar Edamana
 * Distributed under GNU General Public License, version 3
 */ 

#include <assert.h>
#include <stdarg.h>
#include <stdbool.h>

#include "image-cairo.h"


void copy_image_to_cairo_surface_argb32(Image *img, cairo_surface_t *surf)
{
	unsigned char *ibuf = cairo_image_surface_get_data(surf);
	int stride = cairo_image_surface_get_stride(surf);

	for (int y = 0; y < img->height; y += 1) {
		for (int x = 0; x < img->width; x += 1) {
			int pixpos = y * stride + 4 * x;
			nan_img_copy_pixel_to_argb32(img, x, y, ibuf + pixpos);
		}
	}

	cairo_surface_mark_dirty(surf);
}

void copy_image_region_to_cairo_surface(Image *img, cairo_surface_t *surf, VaraRect rect)
{
	assert(img);
	assert(surf);

	image_assert_region(img, rect);

	assert(img->width <= cairo_image_surface_get_width(surf));

	assert(img->height <= cairo_image_surface_get_height(surf));
	unsigned char *ibuf = cairo_image_surface_get_data(surf);
	int stride = cairo_image_surface_get_stride(surf);

	switch (cairo_image_surface_get_format(surf)) {
	case CAIRO_FORMAT_RGB24:
	{
		for (int y = rect.y; y < rect.y + rect.h; y += 1) {
			for (int x = rect.x; x < rect.x + rect.w; x += 1) {
				int pixpos = y * stride + 4 * x;
				nan_img_copy_pixel_to_rgb24(img, x, y, ibuf + pixpos);
			}
		}
		break;
	}

	case CAIRO_FORMAT_ARGB32:
	{
		for (int y = rect.y; y < rect.y + rect.h; y += 1) {
			for (int x = rect.x; x < rect.x + rect.w; x += 1) {
				int pixpos = y * stride + 4 * x;
				nan_img_copy_pixel_to_argb32(img, x, y, ibuf + pixpos);
			}
		}
		break;
	}

	default: {
		assert(false);
		break;
	}
	}

	cairo_surface_mark_dirty_rectangle(surf, rect.x, rect.y, rect.w, rect.h);
}

VaraFileIOError write_image_to_png(Image *img, const char *fname)
{
	cairo_surface_t *surf = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, img->width, img->height);

	copy_image_region_to_cairo_surface(img, surf, image_get_region(img));
	int stat = cairo_surface_write_to_png(surf, fname);

	if (surf) {
		cairo_surface_destroy(surf);
	}

	return (stat == CAIRO_STATUS_SUCCESS)? VARA_FILE_IO_ERROR_SUCCESS: VARA_FILE_IO_ERROR_OTHER;
}
