# Copyright (C) 2006 Affelio Inc.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#

package Diary;
{
    use strict;
    use Image::Magick;

    use Affelio::misc::Debug qw( debug_print);

    ######################################################################
    #run_showimage
    ######################################################################
    sub run_showimage{
	my $self = shift;
	my $afap = $self->{afap};
	my $cgi = $self->{cgi};
	my $wi = $self->{wi};
	
	debug_print("Diary::ShowImage: start");

	###########################
	#Check DF_access
	###########################
	unless ($afap->check_access("DF_access")) {
	    $self->accessErrorExit('Access Denied. You don\'t have permission to this application.');
	}   

	my $id = $wi->PTN_num($cgi->url_param("id"));
	my $filename = $wi->PTN_basefilename($cgi->url_param("filename"));
	my $width  = $wi->PTN_num($cgi->url_param("w"));
	my $height = $wi->PTN_num($cgi->url_param("h"));
	my $size = $wi->PTN_mode($cgi->url_param("size"));
	my $type = $filename;
	$type =~ s/[^.]+\.(.*)/$1/i;
	$type =~ s/jpg/jpeg/i;
	my $filepath;
	my $thumbpath;

	if ($id eq '0'){
	    $filepath = "$self->{datadir}tmp/".$filename;
	    $thumbpath = "$self->{datadir}tmp/thumb/".$filename;
	}else{
	    $filepath = "$self->{datadir}img/$id/".$filename;
	    $thumbpath = "$self->{datadir}img/$id/thumb/".$filename;
	}


	binmode STDOUT;
	print "Content-type: image/$type\n\n";
	if ($size eq "s"){
	    &output_img($thumbpath);
	}
	elsif ($width and $height and (eval 'use Image::Magick; 1;')) {
	    try {
		my $image = new Image::Magick;
		$image->Read(filename => $filepath);
		my ($w, $h) = $image->Get('columns', 'rows');
		if ($w > $width or $h > $height) {
		    $image->Resize(geometry => $width.'x'.$height);
		    $image->Set(quality => 75);
		}
		$image->Write(file => \*STDOUT);
	    }
	    catch Error with {
		my $e = shift;
		&output_img($filepath);
	    };
	}
	else {
	    &output_img($filepath);
	}


	debug_print("Diary::ShowImage: end");

}

sub output_img {
	my $file = shift;
	local (*IMG);
	open(IMG, "$file") or die;
	binmode IMG;
	print while (<IMG>);
	close(IMG);
}


}
1;
