package Memories::Photo;
use Apache2::Upload;
use File::Basename;
use File::Copy;
use Archive::Any;
use File::Temp qw(tempdir tmpnam);
use File::Path qw(rmtree);
use File::Find;
use File::MMagic;
use Image::Size qw(imgsize);
use strict;
use Carp qw(cluck confess);
use base qw(Memories::DBI Maypole::Model::CDBI::Plain);
use constant INTERESTINGNESS_ALGORITHM => '((rating+3)/(rated+1))*(1+rated/hit_count)*(1+hit_count/(select max(hit_count) from photo))';
use Time::Piece;
use Image::Seek;
use constant PAGER_SYNTAX => "LimitXY";
__PACKAGE__->columns(Essential => qw(id title uploader uploaded x y rating rated hit_count format));
__PACKAGE__->untaint_columns(printable => [qw/title/]);
__PACKAGE__->columns(TEMP => qw/exif_object/);

BEGIN {
my %order_by = (
     recent => "uploaded",
     popular => "hit_count",
     loved => "rating/(1+rated)",
     interesting => INTERESTINGNESS_ALGORITHM,
     random => "rand()"
);

while (my($label, $how) = each %order_by) {
    __PACKAGE__->set_sql($label => qq{
    SELECT __ESSENTIAL__
    FROM __TABLE__
    ORDER BY $how DESC
    LIMIT 4
    });
    no strict;
    *$label = sub {
        my ($self, $r) = @_;
        $self->view_paged_ordered($r, "$how desc");
    };
    __PACKAGE__->MODIFY_CODE_ATTRIBUTES(*{$label}{CODE}, "Exported"); # Hack
}
}
__PACKAGE__->has_many(comments => "Memories::Comment");
__PACKAGE__->has_a(uploader => "Memories::User");
__PACKAGE__->has_a(uploaded => "Time::Piece",
    inflate => sub { Time::Piece->strptime(shift, "%Y-%m-%d %H:%M:%S") },
    deflate => 'datetime',
);

sub do_upload :Exported {
    my ($self, $r) = @_;
    my $upload = $r->{ar}->upload("photo");
    # Check $self->type
    my @photos = ($self->upload_file($r, $upload->tempname, $upload->filename));
    my @quarantined = grep { !$_->tags } @photos;
    # Set it up to go again
    if (@quarantined) { 
        $r->{session}{quarantined} = join ",", sort map { $_->id} @quarantined;
        $r->objects(\@quarantined);
        $r->template("quarantine");
        return;
    }
    $r->objects(\@photos);
    if (@photos == 0) { $r->template("upload"); return  }
    if (@photos > 1) { $r->template("list") } 
    else { $r->template("view"); }
    $r->message("Thanks for the upload!"); 
}

sub quarantine :Exported {
    my ($self, $r) = @_;
    my @quarantined = split /,/, $r->{session}{quarantined};
    my %q = map { $_ => 1 } @quarantined;
    for (map /(\d+)/,grep /tags\d+/, keys %{$r->{params}}) {
        my $tags = $r->{params}{"tags$_"};
        next unless $tags;
        if (my $photo = $self->retrieve($_)) {
            $photo->add_tags($tags);
            delete $q{$_};
        }
    }
    $r->{session}{quarantined} = join ",", sort keys %q;
    if (!$r->{session}{quarantined}) {
        $r->template("list");
        $r->objects([ map { $self->retrieve($_) } @quarantined ]);
    } else {
        $r->objects([ map { $self->retrieve($_) } sort keys %q ]);
    }
}

sub upload_file {
    my ($self, $r, $filename, $offered_name) = @_;
    my $mm = File::MMagic->new;
    my $res = $mm->checktype_filename($filename);
    if ($res =~ m{/x-zip} or $offered_name =~ /t(ar\.)?gz$/i) {
        return $self->upload_archive($r, $filename);
    } elsif ($offered_name =~ /\.(raw|nef|dng|cr2)/i) {
        return $self->upload_raw($r, $filename, $offered_name);
    } elsif ($res =~ m{image/jpeg}) {
        return $self->upload_jpeg($r, $filename, $offered_name);
    } else {
        $r->message(basename($offered_name).": I can't handle $res files yet");
        return ();
    }
}

sub upload_archive {
    my ($self, $r, $filename, $tags) = @_;
    $r->{params}{title} = ""; # Kill that dead.
    my $archive = Archive::Any->new($filename);
    my $dir = tempdir();
    $archive->extract($dir);
    my @results; 
    find({ wanted   => sub { return unless -f $_; 
                             push @results, $self->upload_file($r, $_, $_) }, 
           no_chdir => 1}, $dir);
    rmtree($dir);
    return @results;
}

sub upload_raw {
    my ($self, $r, $filename, $offered_name) = @_;
    my $jpg = tmpnam().".jpg";
    system("dcraw -c $filename | convert - $jpg");
    $filename =~ /\.(.*)$/;
    my $format = $1;
    # Put the file in place
    $photo->format($format);
    copy($filename, 
         Memories->config->{data_store}."/".$photo->id.".".$format);
    my $photo = $self->upload_jpeg($r, $jpg, $offered_name);
    return $photo;
}

sub upload_jpeg {
    my ($self, $r, $filename, $offered_name) = @_;
    my $photo = $self->create({
        uploader => $r->user,
        uploaded => Time::Piece->new(),
        title => ($r->{params}{title} || basename($offered_name)),
        hit_count => 0,
        rating => 0,
        rated => 0,
    });
    if (!copy($filename, $photo->path("file"))) {
	warn "Couldn't copy photo to ".$photo->path("file").": $!";
        $photo->delete(); die;
    }
    my ($x, $y, undef) = imgsize($photo->path);
    $photo->x($x); $photo->y($y);

    # Rotate?
    $photo->unrotate(); 
    if (!$photo->title){ 
        $photo->title($photo->title_exif || basename($filename));
    }

    $photo->make_thumb;
    my $tags = $r->{params}{tags}.join " ", map { qq{"$_"} } $photo->tags_exif;
    $photo->add_tags($tags);
    $photo->add_to_imageseek_library;
    Memories->zap_cache();
    # Add system tags here
    my $tag = "date:".$photo->shot->ymd;
    $photo->add_to_system_tags({tag => Memories::SystemTag->find_or_create({name =>$tag}) });
    return $photo;
}

sub approx_rating {
    my $self = shift;
    $self->rated or return 0;
    int($self->rating/$self->rated*10)/10;
}

sub add_rating :Exported {
    my ($self, $r) = @_;
    my $photo = $r->{objects}[0];
    my $delta = $r->{params}{rating};
    if ($delta < 0 or $delta > 5) { return; } # Scammer
    # XXX Race
    $photo->rating($photo->rating() + $delta);
    $photo->rated($photo->rated() + 1);
    $r->output(""); # Only used by ajax
}

sub view :Exported {
    my ($self, $r) = @_;
    my $photo = $r->{objects}[0];
    $photo->hit_count($photo->hit_count()+1);
    if ($r->{session}{last_search}) {
        # This is slightly inefficient
        my @search = split/,/, $r->{session}{last_search};
        my $found = -1;
        for my $i (0..$#search) {
            next unless $photo->id == $search[$i];
            $found = $i;
        }
        return unless $found > -1;
        $r->{template_args}{next} = $self->retrieve($search[$found+1]) 
            if $found+1 <= $#search;
        $r->{template_args}{prev} = $self->retrieve($search[$found-1])
            if $found-1 >= 0;
    }
}
sub upload :Exported {}
sub exif :Exported {}
sub comment :Exported {}
sub tagedit :Exported {}
sub similar :Exported {}
sub sized :Exported {}

use Class::DBI::Plugin::Pager;
use Class::DBI::Plugin::AbstractCount;

sub view_paged_ordered {
    my ($self, $r, $how) = @_;
    my $page = $r->params->{page} || 1;
    my $pager = $self->pager(
        per_page => Memories->config->{photos_per_page}, 
        page => $page,
        syntax => PAGER_SYNTAX,
        order_by => $how
    );
    $r->objects([$pager->retrieve_all ]);
    $r->{template_args}{pager} = $pager;
    $r->last_search;
    $r->template("paged"); # Set the what using the action name
}

sub add_comment :Exported {
    my ($self, $r, $photo) = @_;
    $r->template("view");
    $r->objects->[0]->add_to_comments({
        name => $r->params->{name},
        content => $r->params->{content}
    });
}

use Cache::MemoryCache;
use Image::ExifTool;
my $cache = new Cache::MemoryCache( { 'namespace' => 'MemoriesInfo' });

sub add_to_imageseek_library {
    my $self = shift;
    Image::Seek::cleardb();
    my $img = Image::Imlib2->load($self->path("file"));

    Image::Seek::add_image($img, $self->id);
    # Merge this new one into the main database; there is a bit of a
    # race condition here. XXX
    Image::Seek::loaddb(Memories->config->{image_seek});
    Image::Seek::savedb(Memories->config->{image_seek});
}

sub recommended_tags {
    my $self = shift;
    my %tags = map { $_->name => $_ }
               map { $_->tags } 
               $self->find_similar(3);
    values %tags;
}

sub find_similar {
    my ($self, $count) = @_;
    Image::Seek::cleardb();
    Image::Seek::loaddb(Memories->config->{image_seek});
    my @res = map {$_->[0] } Image::Seek::query_id($self->id, $count);
    shift @res; # $self
    map { $self->retrieve($_) } @res;
}

sub unrotate {
    my $self = shift;
    my $orient = $self->exif_info->{EXIF}->{Orientation};
    return if $orient !~/Rotate (\d+)/i;
    my $steps = $1/90;
    my $img = Image::Imlib2->load($self->path("file"));
    $img->image_orientate($steps);
    $img->save($self->path("file"));
}

sub exif_info {
    my $self = shift;
    my $info = $self->exif_object;
    return $info if $info;
    # Get it from the Cache
    if (!($info = $cache->get($self->id))) {
        # Create it
        $info = $self->_exif_info;
        $cache->set($self->id, $info);
    }
    $self->exif_object($info);
    $info;
}

my %banned_tags = map { $_ => 1 }
    qw( CodedCharacterSet ApplicationRecordVersion );

sub _exif_info {
    my $exifTool = new Image::ExifTool;
    $exifTool->Options(Group0 => ['IPTC', 'EXIF', 'XMP', 'MakerNotes', 'Composite']);
    my $info = $exifTool->ImageInfo(shift->path(0,0,1));
    my $hash = {};
    foreach my $tag ($exifTool->GetFoundTags('Group0')) {
        next if $banned_tags{$tag};
         my $group = $exifTool->GetGroup($tag);
         my $val = $info->{$tag};
         next if ref $val eq 'SCALAR';
         next if $val =~ /^[0\s]*$/ or $val =~ /^nil$/;
         $hash->{$group}->{$exifTool->GetDescription($tag)} = $val;
    }
    return $hash;
}

# XXX Cache this
sub dimensions { join "x", $_[0]->x, $_[0]->y }

sub is_bigger {
    my ($self, $size) = @_;
    return 1 if $size eq "full";
    my ($w, $h) = ($self->x, $self->y);
    my ($w2, $h2) = split /x/, $size;
    return 1 if $w > $w2 or $h > $h2;
    return 0;
}

sub sized_url { # Use this rather than ->path from TT
    my ($self, $size) = @_;
    my $url = Memories->config->{data_store_external};
    my $resized = Memories->config->{sizes}->[$size];
    if (!$resized) { cluck "Asked for crazy size $size"; return; }
    if ($resized eq "full") { return $self->path("url") }
    $self->scale($resized) 
        unless -e $self->path( file => $resized );
    return $self->path(url => $resized);
}

sub path { 
    my ($self, $is_url, $scale, $raw) = @_;
    my $path =
        Memories->config->{$is_url eq "url" ? "data_store_external" : "data_store" };
    if ($scale) { $path .= "$scale/" }
    # Make dir if it doesn't exist, save trouble later
    use File::Path;
    if ($is_url ne "url" and ! -d $path) {mkpath($path) or die "Couldn't make path $path: $!";}
    if ($scale or ($is_url ne "url" and !$raw)) { 
        $path .= $self->id.".jpg";
    } else {
        $path .= $self->id.".".($self->format||"jpg");
    }
    return $path;
}

sub thumb_url { shift->path(url => Memories->config->{thumb_size}); }
sub make_thumb { shift->scale(Memories->config->{thumb_size}, 1); }

use Image::Imlib2;
sub scale {
    my ($self, $scale, $swap) = @_;
    my ($x, $y) = split /x/, $scale;
    # Find out smaller axis
    my ($cur_x, $cur_y) = ($self->x, $self->y);
    if (!$swap) {
        if ($cur_x < $cur_y) { $y = 0 } else { $x = 0 }
    } else {
        if ($cur_x > $cur_y) { $y = 0 } else { $x = 0 }
    }
    my $img = Image::Imlib2->load($self->path("file"));
    unless ($img) {
        cluck "Couldn't open image file ".$self->path("file");
        return;
    }
    $img = $img->create_scaled_image($x, $y);
    $img->image_set_format("jpeg");
    my $file = $self->path( file => $scale );
    $img->save($file);
    if ($!) {
        cluck "Couldn't write image file $file ($!)"; 
        return;
    }
}

sub edit_tags :Exported {
    my ($self, $r) = @_;
    my $photo = $r->objects->[0];
    my %params = %{$r->params};
    my $exifTool = new Image::ExifTool;
    for (keys %params) { 
        next unless /delete_(\d+)/;
        my $tagging = Memories::Tagging->retrieve($1) or next;
        next unless $tagging->photo->id == $photo->id;
        $exifTool->SetNewValue(Keywords => $1, DelValue => 1);
        $tagging->delete;
    }
    $exifTool->WriteInfo($photo->path);
    $photo->add_tags($params{newtags});
    $r->template("view");
}

sub add_tags {
    my ($photo, $tagstring) = @_;
    my $exifTool = new Image::ExifTool;

    for my $tag (Tagtools->separate_tags($tagstring)) {
        $photo->add_to_tags({tag => Memories::Tag->find_or_create({name =>$tag}) });
        $exifTool->SetNewValue(Keywords => $tag, AddValue => 1);
    }
    $exifTool->WriteInfo($photo->path);
}

# Work out some common properties from a set of potential photo metadata
# tags
sub _grovel_metadata {
    my ($self, @tags) = @_;
    my %md = map {%$_} values %{$self->exif_info};
    for (@tags) {
        if ($md{$_} and $md{$_} =~/[^ 0:]/) { return $md{$_} }
    }
    return;
}

sub shot {
    my $self = shift;
    my $dt = $self->_grovel_metadata(
        'Shooting Date/Time',
        'Date/Time Of Digitization',
        'Date/Time Of Last Modification'
    );
    if (!$dt) { return $self->uploaded }
    return Time::Piece->strptime($dt, "%Y:%m:%d %T") || $self->uploaded;
}

sub description {
    shift->_grovel_metadata(
        'Description', 'Image Description', 'Caption-Abstract'
    );
}

sub title_exif { shift->_grovel_metadata( 'Headline', 'Title'); }
sub license { shift->_grovel_metadata( 'Rights Usage Terms', 'Usage Terms' ) }
sub copyright { shift->_grovel_metadata( 'Rights', 'Copyright', 'Copyright Notice') }

# This one's slightly different since we want everything we can get...
sub tags_exif {
    my $self = shift;
    my %md = map {%$_} values %{$self->exif_info};
    my %tags = 
        map { s/\s+/-/g; lc $_ => 1  }
        map { split /\s*,\s*/, $md{$_}}
        grep {$md{$_} and $md{$_} =~/[^ 0:]/}
        (qw(Keywords Subject City State Location Country Province-State), 
        'Intellectual Genre', 
        'Country-Primary Location Name'
        );
    return keys %tags;
}
1;
