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

void image_view_construct(ImageView *this)
{
	this->_ngg_vtab_image_view.destruct = (void (*)(ImageView *this)) image_view__nggnonvirt_destruct;
	this->da = (GtkDrawingArea *) gtk_drawing_area_new();
	this->surf = NULL;
	this->img = NULL;
	this->autoresize = true;

	g_signal_connect((GtkWidget *) (this->da), "destroy", G_CALLBACK(image_view_on_da_destroy), NULL);
	g_signal_connect((GtkWidget *) (this->da), "draw", G_CALLBACK(image_view_on_da_draw), this);
	gtk_widget_show((GtkWidget *) (this->da));
}

GtkWidget * image_view_get_native_widget(ImageView *this)
{
	return (GtkWidget *) (this->da);
}

void image_view_on_da_destroy(GtkWidget *widget, void *user_data)
{
	ImageView *me = (ImageView *) user_data;
	if (me) {
		((ImageView *) me)->_ngg_vtab_image_view.destruct((ImageView *) me);
		free(me);
		me = NULL;
	}
}

void image_view_on_da_draw(GtkDrawingArea *widget, cairo_t *nggevent_cr, void *user_data)
{
	if (((ImageView *) user_data)->surf) {
		cairo_surface_t *surfnn;
		surfnn = (cairo_surface_t *) (((ImageView *) user_data)->surf);
		cairo_set_source_surface(nggevent_cr, surfnn, 0, 0);
		cairo_paint(nggevent_cr);
	}
}

void image_view_set_image(ImageView *this, Image *img)
{
	Image *_ngg_tmp_0 = img;
	if (this->img) {
		image_destruct((Image *) (this->img));
		free(this->img);
	}

	this->img = _ngg_tmp_0;

	cairo_surface_t *_ngg_tmp_1 = gdk_window_create_similar_image_surface(gtk_widget_get_window((GtkWidget *) (this->da)), CAIRO_FORMAT_ARGB32, img->width, img->height, 0);
	if (this->surf) {
		cairo_surface_t *_tmp_1 = (cairo_surface_t *) (this->surf);
		cairo_surface_destroy(_tmp_1);
	}

	this->surf = _ngg_tmp_1;

	assert(this->surf);
	if (this->autoresize) {
		gtk_widget_set_size_request((GtkWidget *) (this->da), img->width, img->height);
	}

	image_view_queue_draw(this);
}

void image_view_queue_draw(ImageView *this)
{
	assert(this->img);
	assert(this->surf);
	copy_image_to_cairo_surface_argb32(this->img, this->surf);
	gtk_widget_queue_draw((GtkWidget *) (this->da));
}

void image_view_show(ImageView *this)
{
	gtk_widget_show((GtkWidget *) (this->da));
}

void image_view__nggnonvirt_destruct(ImageView *this)
{
	if (this->img) {
		image_destruct((Image *) (this->img));
		free(this->img);
	}

	if (this->surf) {
		cairo_surface_t *_tmp_1 = (cairo_surface_t *) (this->surf);
		cairo_surface_destroy(_tmp_1);
	}
}

void image_view_destruct(ImageView *this)
{
	this->_ngg_vtab_image_view.destruct(this);
}
