package Shiar_Sheet::ImagePrep;

use 5.014;
use warnings;

our $VERSION = '1.01';

sub new {
	my ($class, $target) = @_;
	bless \$target, $class;
}

sub download {
	# copy changed remote url to local file
	my $target = shift;
	unlink $$target if -e $$target;
	my $download = shift or return 1;
	require LWP::UserAgent;
	my $ua = LWP::UserAgent->new;
	$ua->agent('/');
	my $status = $ua->mirror($download, $$target);
	$status->is_success
		or die "Download from <q>$download</q> failed: ".$status->status_line."\n";
}

sub dimensions {
	my ($imgpath) = @_;
	require IPC::Run;
	IPC::Run::run(
		[identify => -format => '%w %h', $$imgpath],
		'<' => \undef, '>&' => \my $xy
	) or die ["Image dimensions could not be determined.", $$imgpath];
	return split /\s/, $xy, 3;
}

sub convert {
	my ($imgpath, $thumbpath, $cmds, $xyres) = @_;
	if (not -e $$imgpath) {
		return !-e $thumbpath || unlink $thumbpath;
	}

	#my ($w, $h) = $imgpath->dimensions;
	$xyres //= '300x200'; # cover
	my $aspect = 3/2;
	my @cmds = @{ $cmds // [] };
	if (my ($cmdarg) = grep { $cmds[$_] eq '-area' } 0 .. $#cmds) {
		# replace option by permillage crop
		my @dim = map { $_ / 1000 } split /\D/, $cmds[$cmdarg + 1];
		$dim[$_] ||= 1 for 2, 3; # optional end
		push @dim, $dim[2 + $_] - $dim[$_] for 0, 1; # add width, height
		splice @cmds, $cmdarg, 2, (
			#crop="%[fx:floor(w*$ratio)]x%[fx:floor(h*$ratio)]"
			#crop="$crop+%[fx:ceil((w-w*$ratio)/2)]+%[fx:ceil((h-h*$ratio)/2)]"
			-set => 'option:distort:viewport' => sprintf(
				'%%[fx:%s]x%%[fx:%s]+%%[fx:%s]+%%[fx:%s]',
				"w*$dim[4]", "h*$dim[5]", # width x height
				#"max(w*$dim[4], h*$dim[5]*$aspect)", # width
				#"max(h*$dim[5], w*$dim[4]/$aspect)", # height
				"w*$dim[0]", "h*$dim[1]", # x+y offset
			),
			-distort => SRT => 0, # noop transform to apply viewport
		);
	}
	@cmds = (
		'convert',
		$$imgpath,
		-delete => '1--1', -background => 'white',
		-gravity => defined $cmds ? 'northwest' : 'center',
		@cmds,
		-resize => "$xyres^", -extent => $xyres,
		'-strip', -quality => '60%', -interlace => 'plane',
		$thumbpath
	);

	require IPC::Run;
	my $output;
	IPC::Run::run(\@cmds, '<' => \undef, '>&' => \$output) or die [
		"Failed to convert source image.",
		"@cmds\n" .
		($output || ($? & 127 ? "signal $?" : "error code ".($? >> 8))),
	];
}

1;
