package LATMOS::Accounts::Web::Controller::Groups;

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

=head1 NAME

LATMOS::Accounts::Web::Controller::Groups - Catalyst Controller

=head1 DESCRIPTION

Catalyst Controller.

=head1 METHODS

=cut


=head2 index 

=cut

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

    $c->stash->{ofilter} = $c->model('AttrFilter', 'group');
    $c->stash->{groupslist} = [  map { $_->id } @{ $c->stash->{objectslist} } ];

}

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

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

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

    for ($subform || '') {
        # Exceptions...
        /^users$/ and do {
            $c->stash->{template} = 'groups/users.tt';

            my %ingroup = map { $_ => 1 } @{
                $c->stash->{group}->get_c_field('memberUID') || [] };
            if ($c->req->param('adduser')) {
                $c->stash->{group}->set_c_fields('memberUID' => [ (keys %ingroup), $c->req->param('adduser') ]);
                $c->stash->{group}->base->commit;
                %ingroup = map { $_ => 1 } @{ $c->stash->{group}->get_c_field('memberUID') };
            } elsif ($c->req->param('deluser')) {
                $c->stash->{group}->set_c_fields('memberUID',
                    [ grep { $_ ne $c->req->param('deluser') } keys %ingroup ]
                );
                $c->stash->{group}->base->commit;
                %ingroup = map { $_ => 1 } @{ $c->stash->{group}->get_c_field('memberUID') };
            }

            $c->stash->{add_user_list} = [ grep { ! $ingroup{$_} } $base->list_objects('user') ];
            last;
        };

        $c->stash->{form} = $c->model('AttrForms', 'group' . $c->stash->{subform}, $c->stash->{group});
        $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;
