package Memories::User;
use base qw(Memories::DBI Maypole::Model::CDBI::Plain);
__PACKAGE__->columns(All => qw/id name password/);
__PACKAGE__->has_many(photos => "Memories::Photo");

sub register :Exported {
    my ($class, $r) = @_;
    my $login = $r->params->{name};
    my $pass  = $r->params->{password};
    $r->template("frontpage");
    return if $r->user;

    # Do we already exist?
    if (!$login) { $r->template("login"); $r->message("You didn't enter a user name"); return; }
    my ($user) = $class->search(name => $login);
    if ($user) { $r->template("login"); $r->message("User name already exists"); return; }
    $user = $class->create({name => $login, password => $pass });
    $r->user($user, 0);
    $r->login_user($user->id);

}

sub view :Exported {
    my ($self, $r) = @_;
    my $user = $r->objects->[0]; 
    my $page = $r->params->{page} || 1;
    my $pager = Class::DBI::Pager::_pager("Memories::Photo",
        Memories->config->{photos_per_page}, $page); 
    $r->{template_args}{photos} = [$pager->search(uploader =>
    $user->id,{order_by => "uploaded desc"}) ];
    $r->{template_args}{pager} = $pager;
    $r->{template_args}{albums} = [$user->albums(privacy => 0)];
}

# Album support!

sub edit_albums :Exported {
    my ($self, $r) = @_;
    $r->{template} = "view";
    $self->view($r);
    my $user = $r->objects->[0];
    return unless $r->user and $r->user->id == $user->id;
    if ($r->{params}{create}) {
        $user->add_to_albums({
            privacy => !!($r->{params}{new_privacy}),
            name => $r->{params}{new_name}
        });
    } elsif ($r->{params}{changes}) {
        for my $album ($user->albums) { #XXX
            warn "Setting $album privacy to ".
                $r->{params}{"privacy_".$album->id};
            $album->privacy(!!$r->{params}{"privacy_".$album->id});
        }
    } else {
        my @to_delete = map /(\d+)/,
            grep /delete_\d+/, keys %{$r->{params}};
        for (@to_delete) {
            my $album = Memories::Album->retrieve($_);
            if ($album and $album->user->id == $user->id) {
                $album->delete
            }
        }
    }
    
}

1;
