package PhotoPub::Display;
require Exporter;
@ISA = qw(Exporter);
@EXPORT_OK = qw(&checkimageoptions &display);

use PhotoPub::Global qw($error);
use PhotoPub::Images qw(&picfile);
use PhotoPub::Options qw(&initoptions &setoptions);
use PhotoPub::Cache qw(&imagefile);
use PhotoPub::Ages qw(&updateagefromfiles);
use PhotoPub::Display qw(&checkimageoptions);
use PhotoPub::Utils qw(&untaint &makeabsolutepath);

use strict;

my %image_entries=
  (
   'shrink' => ['\d+','shrink must be a positive integer'],
   'gamma' => ['[\d\.]+','gamma must be a positive number'],   
   'red' => ['[\d\.]+','red must be a positive number'],
   'green' => ['[\d\.]+','green must be a positive number'],
   'blue' => ['[\d\.]+','blue must be a positive number'],
   'rotate' => ['[\d\.]+a?',"rotate must be a positive integer "
		."with an optional 'a' at the end to select automatic"
		."cropping"],
   'thumb' => ['\d+x\d+','thumb must in the format <m>x<n> where '
	       .'<m> and <n> are positive integers'],
   'crop' => ['[x\d\+\-\%]+','crop must match the regexp [x\d\+\-\%]+'],
   'sharpen' => ['[\d\.]+','sharpen must be a positive number'],
   'quality' => ['\d+','quality must be a positive integer']
  );

sub checkimageoptions {
  my ($options)=@_;
  my $output={};

  foreach my $entry (keys %image_entries) {
    my $value=$options->{$entry};
    if(defined $value) {
      untaint(\$value,@{$image_entries{$entry}});
      $output->{$entry}=$value;
    }
  }

  &$error(type=>'userinput',message=>"shrink must be between 1 and 100") 
    if(defined $output->{'shrink'} && 
       ($output->{'shrink'}<1 || $output->{'shrink'}>100));

  if(defined $output->{'rotate'}) {
    $output->{'rotate'}=~/^(\d+)/;
    &$error(type=>'userinput',
	    message=>"rotate must be 0 or greater and less than 360")
      if $1<0 || $1>359;
  }

  if(defined $output->{'sharpen'}) {
    $output->{'sharpen'}=~/^(\d+)/;
    &$error(type=>'userinput',
	    message=>"sharpen must be 0 or greater and less than 100")
      if $1<0 || $1>99;
  }
  return $output;
}

sub display {
  my ($options)=@_;

  my $photo=$options->{'photo'}
    or &$error(type=>'userinput',message=>'Must give a photo!');

  &makeabsolutepath(\$photo);

  my $image_options=&initoptions();

  my $image_options_from_query=&checkimageoptions($options);

  while(my ($entry,$value)=each %$image_options_from_query) {
    &setoptions($image_options,{$entry => $value});
  }


  return &imagefile($photo,$image_options);
}
