package LATMOS::Accounts::Web::Controller::Users;

use strict;
use warnings;
use base 'LATMOS::Accounts::Web::Controller';

=head1 NAME

LATMOS::Accounts::Web::Controller::Users - Catalyst Controller

=head1 DESCRIPTION

Catalyst Controller.

=head1 METHODS

=cut


=head2 index 

=cut

sub index : Private {
    my ( $self, $c ) = @_;

    $c->stash->{ofilter} = $c->model('AttrFilter', 'user');
    my $start = ($c->req->param('start') || '0') * 20 ;
    $c->stash->{uparams} = { %{ $c->req->params || {} } };
    my @userlist = map { $_->id } @{ $c->stash->{objectslist} };
    $c->stash->{pagecount} = int(@userlist / 20);
    splice(@userlist, 0, $start) if($start);
    $c->stash->{userslist} = [
        @userlist[0 .. ($#userlist > 19 ? 19 : $#userlist)]
    ];
}

sub default : LocalPath {
    my ( $self, $c, undef, $username, $subform, $arg ) = @_;

    my $base = $c->model('Accounts')->db;

    $c->stash->{username} = $username;
    $c->stash->{user} = $base->get_object('user', $username);
    $c->stash->{subform} = $subform || '';

    for ($subform || '') {
        # Exceptions...
        /^passwd$/ and do {
            $c->stash->{template} = 'users/passwd.tt';
            if ($c->req->param('passwd')) {
                if ($c->req->param('passwd') eq ($c->req->param('cpasswd') || '')) {
                    my $sync = $c->model('Accounts')->sync_access;
                    
                    # This is widelly burk:
                    # synchaccess do not manage connect() at time, opening a
                    # backdoor then :\
                    foreach ($sync->bases) { $_->{_user} = $c->user->{username} }
                    
                    my $suser = $sync->get_object('user', $username);
                    my $msg = $c->stash->{user}->check_password($c->req->param('passwd'));
                    if ($msg ne 'ok') {
                        $c->stash->{pmerror} = $msg . ', mot de passe inchangé';
                    } elsif ($suser && $suser->set_password($c->req->param('passwd'))) {
                        $c->stash->{pmerror} = 'Mot de passe changé';
                        $sync->commit;
                    } else {
                        $c->stash->{pmerror} = 'Erreur lors du changement de mot de passe';
                    }
                } else {
                    $c->stash->{pmerror} = 'Mot de passe différents';
                }
            }
            last;
        };
        /^groups$/ and do {
            $c->stash->{template} = 'users/groups.tt';
            # list of group for which users can be added
            my %ingroups = map { $_ => 1 } @{ $c->stash->{user}->get_c_field('memberOf') || []};
            if ($c->req->param('addgroup')) {
                $c->stash->{user}->set_c_fields('memberOf', [ keys %ingroups, $c->req->param('addgroup') ]);
                $c->stash->{user}->base->commit;
                # reread:
                %ingroups = map { $_ => 1 } @{ $c->stash->{user}->get_c_field('memberOf') || []};
            } elsif ($c->req->param('delgroup')) {
                $c->stash->{user}->set_c_fields('memberOf',
                    [ grep { $_ ne $c->req->param('delgroup') } keys %ingroups ]
                );
                $c->stash->{user}->base->commit;
                %ingroups = map { $_ => 1 } @{ $c->stash->{user}->get_c_field('memberOf') || []};
            }

            $c->stash->{othergroups} = [ grep { ! $ingroups{$_} } $base->list_objects('group') ];
            last;
        };
        /^address$/ and do {
            if ($arg) {
                $c->stash->{address} = $base->get_object('address', $arg);
                $c->stash->{form} = $c->model('AttrForms', 'address',
                    $c->stash->{address});
                $c->stash->{template} = 'users/address.tt';
                $c->stash->{form}->set_attrs;
            } else {
                $c->stash->{form} = $c->model('AttrForms', 'address', 'address',
                    $base);
                if ($c->req->param('delete')) {
                    $base->delete_object('address', $c->req->param('delete'));
                    $base->commit;
                } elsif ($c->req->param('create')) {
                    my $addname = $username . join('', map
                        {('a'..'z')[rand(26)]}(0..4));
                    $base->create_c_object('address',
                        $addname,
                        map { $_ => $c->req->param($_) }
                        $c->stash->{form}->attributes('w'),
                        user => $username,
                    );
                    $base->commit;
                    $c->res->redirect($c->uri_for($username, 'address',
                            $addname));
                    return;
                }
                $c->stash->{template} = 'users/addresses.tt';
            }
            last;
        };
        /^mail$/ and do {

            $c->stash->{db} = $base;
            $c->stash->{template} = 'users/mail.tt';

            if ($c->req->param('usermail')) {
                $c->stash->{user}->set_c_fields(
                    mail => $c->req->param('mail') || undef,
                    aliases => [ grep { $_ } $c->req->param('aliases') ],
                    revaliases => $c->req->param('revaliases') || undef,
                    forward => $c->req->param('forward') || undef,
                ) and $base->commit;
            }

            last;
        };

        $c->stash->{form} = $c->model('AttrForms', 'user' . $c->stash->{subform}, $c->stash->{user});
        $c->stash->{form}->set_attrs;
    }
}

=head1 AUTHOR

Thauvin Olivier

=head1 LICENSE

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

=cut

1;
