# cb 040226

package Bilder::Pic;

use strict;
use Image::Size;

sub scale {
	my ($x, $y, $max) = @_;
	die "x undefined" unless defined $x; # value undefined
	return $x unless $max;
	if($x > $y) {
		return $x > $max ? $max : $x;
	} else {
		return $y > $max ? int($x * $max / $y) : $x;
	}
}

sub new
{
	my $args = shift;
	my ($w, $h) = imgsize($args->{pic}.$args->{pic_suffix});
	my $self = {
		args => $args,
		width => $w,
		height => $h,
		TITLE => $args->{title},
		NR => $args->{nr},
		LINK => "$args->{jpg_url}/$args->{specdir}/$args->{specpic}$args->{pic_suffix}",
		WIDTHHEIGHT => imgwidthheight($w, $h, $args->{size}),
		SIZE => ($w > $h ? $w : $h),
	};
	bless $self;
}

sub WIDTH
{
	my $self = shift;
	my $size = shift;
	return scale($self->{width}, $self->{height}, $size);
}

sub HEIGHT
{
	my $self = shift;
	my $size = shift;
	return scale($self->{height}, $self->{width}, $size);
}

sub imgwidthheight {
	my ($w, $h, $max_w) = @_;
	my $max_h = $max_w;
	#($max_w, $max_h) = ($1, $2) if $max_w =~ /(\d+) *, *(\d+)/; TODO
	($w, $h) = ($max_w, int($h * $max_w / $w)) if $max_w and $w > $max_w;
	($w, $h) = (int($w * $max_h / $h), $max_h) if $max_w and $h > $max_h;
	return "width=\"$w\" height=\"$h\"";
}

1;
