package LATMOS::Accounts::Web::Controller::Logs;
use Moose;
use namespace::autoclean;

BEGIN { extends 'Catalyst::Controller'; }

=head1 NAME

LATMOS::Accounts::Web::Controller::Logs - Catalyst Controller

=head1 DESCRIPTION

Catalyst Controller.

=head1 METHODS

=cut

sub auto : Private {
    my ( $self, $c ) = @_;
    my $base = $c->model('Accounts')->db;

    unless ($base->check_acl($c->stash->{user}, 'Log', 'r')) {
        $c->go('/no_object');
        return;
    }

    return 1;
}

=head2 index

=cut

sub index :Path :Args(0) {
    my ( $self, $c ) = @_;

    my $modifier = $c->req->param('modifier');
    my $otype    = $c->req->param('otype');
    my $object   = $c->req->param('object');
    my $okey     = $c->req->param('okey');

    my (@where, @values);
    my $limit = 1000;

    if ($okey) {
        $c->stash->{logobject} = $c->model('Accounts')->db->getObjectFromOKey($okey);
        push(@where, 'ikey = ?');
        push(@values, $okey);
        if (my $obj = $c->stash->{logobject}) {
            $c->req->params->{otype} = $obj->type;
            $c->req->params->{object} = $obj->id;
        }
    } elsif ($otype) {
        push(@where, 'otype = ?');
        push(@values, $otype);

        if ($object) {
            push(@where, '"name" = ?');
            push(@values, $object);

            $c->stash->{logobject} = $c->model('Accounts')->db->get_object($otype, $object);
            $limit = undef;
        }
    }

    if ($modifier) {
        push(@where, '"username" =  ?');
        push(@values, $modifier);
    }

    my $search = $c->model('Accounts')->db->db->prepare_cached(
        sprintf(
            q{select * from objectslogs %s order by logdate desc %s},
            (@where ? 'where ' . join(' and ', @where) : ''),
            ($limit ? "LIMIT $limit" : ''),
        )
    );

    $search->execute(@values);

    $c->stash->{logs} = $search->fetchall_arrayref({});
}



=encoding utf8

=head1 AUTHOR

Olivier Thauvin,Guyancourt - B1428,+33 1 80285052,

=head1 LICENSE

This library is free software. You can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

__PACKAGE__->meta->make_immutable;

1;
