package Memories::Album;
use base qw(Memories::DBI Maypole::Model::CDBI::Plain);
__PACKAGE__->columns(Essential => qw/id name user privacy/);
Memories::Album->has_a(user => "Memories::User");
Memories::User->has_many(albums => "Memories::Album");

sub view :Exported {
    my ($self, $r) = @_;
    my $album = $r->objects->[0];
    if ($album->privacy && $album->user != $r->user) {
        $r->template("denied"); return;
    }
    $r->template_args->{photos} = [ $album->photos ];
}

sub list :Exported {
    my ($self, $r) = @_;
    my $page = $r->{params}{page} || 1;
    my $pager = Memories::Album->pager(
        Memories->config->{photos_per_page}, $page);
    $r->{objects} = [$pager->search(privacy => 0)];
    $r->{template_args}{pager} = $pager;
}

sub edit :Exported {
    my ($self, $r) = @_;
    use Data::Dumper; warn Dumper($r->{params});
    my $album;
    if ($r->{params}{album}) { # We're adding to an album
        $album = $self->retrieve($r->{params}{album});
        if (!$album or $album->user != $r->user) { 
            $r->template("denied"); return;
        }
        for (map /(\d+)/,grep /add\d+/, keys %{$r->{params}}) {
            Memories::AlbumEntry->create({
                    album => $album->id,
                    photo => $_
                });
        }
    } else {
        $album = $r->{objects}[0];
        if (!$album or $album->user != $r->user) { 
            $r->template("denied"); return;
        }
        for (map /(\d+)/,grep /delete\d+/, keys %{$r->{params}}) {
            my ($ae) = Memories::AlbumEntry->search({
                    album => $album->id,
                    photo => $_
                });
            $ae->delete if $ae;
        }
    }
    $r->objects([ $album ]);
    $r->template("view"); $self->view($r);
}

package Memories::AlbumEntry;
use base qw(Memories::DBI);
__PACKAGE__->table("album_entry");
__PACKAGE__->columns(TEMP => qw/count/);
__PACKAGE__->columns(Essential => qw/id album photo/);
__PACKAGE__->set_sql(summary => qq/
SELECT  id, album, count(*) AS count
FROM album_entry;
GROUP BY album
ORDER BY count DESC
LIMIT 50
    /);
Memories::AlbumEntry->has_a("photo" => "Memories::Photo");
Memories::AlbumEntry->has_a("album" => "Memories::Album");

Memories::Photo->has_many(albums => ["Memories::AlbumEntry" => "album"]);
Memories::Photo->has_many(albumentries => "Memories::AlbumEntry");
Memories::Album->has_many(photos => ["Memories::AlbumEntry" => "photo"] );
Memories::Album->has_many(albumentries => "Memories::AlbumEntry");

1;
