package LATMOS::Accounts::Web::Model::AttrFilter;

use strict;
use warnings;
use base 'Catalyst::Model';

=head1 NAME

LATMOS::Accounts::Web::Model::AttrFilter - Catalyst Model

=head1 DESCRIPTION

Catalyst Model.

=cut

my $fields = {
    user => [ qw(uid sn givenName description uidNumber gidNumber company department manager) ],
    group => [ qw(cn description gidNumber sutype) ],
    site => [ qw(l) ],
};

sub new {
    my ($class) = @_;
    return bless({}, $class);
}

sub ACCEPT_CONTEXT {
    my ($self, $c, $otype) = @_;

    my $new = {};
    $new->{c} = $c;
    $new->{otype} = $otype;
    $c->stash->{filter} = {
        otype => $otype,
    } unless($c->stash->{filter});
    if (exists($c->req->params->{'attr'})) {
        $c->stash->{filter}{'attr'} = [ $c->req->param('attr') ];
        $c->stash->{filter}{'attrval'} = [ $c->req->param('attrval') ];
    }
    
    $c->stash->{ofilter} = bless($new, __PACKAGE__);
    $c->stash->{db} ||= $c->model('Accounts')->db;
    my $base = $c->stash->{db};

    my @filter = $c->stash->{ofilter}->filter;
    $c->stash->{objectslist} = [
        map { $base->get_object($otype, $_) }
        (@filter
            ? ($base->search_objects($otype, @filter) )
            : ($base->list_objects($otype) ))
    ];

    $c->stash->{ofilter}
}

sub otype {
    my ($self) = @_;
    $self->{otype};
}

sub submit {
    my ($self) = @_;
    return sprintf(
        '<input type="submit" name="%s">',
        $self->escape($self->label),
    );
}

sub current_value {
    my ($self) = @_;
    my @vals = @{ $self->{c}->stash->{filter}{attrval} || [] };
    my @fies = @{ $self->{c}->stash->{filter}{attr} || [] };
    my @couples;
    foreach (@fies) {
        my $val = shift(@vals);
        $_ && $val or next;
        push(@couples, { f => $_, v => $val});
    }
    push(@couples, {});
    @couples;
}

sub count_field {
    my ($self) = @_;
    return [ (0 .. (scalar($self->current_value) -1)) ];
}

sub search_field {
    my ($self, $count) = @_;
    my $form = $self->{c}->model('AttrForms');
    my $html = '<select name="attr">
    <option value=""></option>';
    my @values = $self->current_value;
    foreach (@{ $fields->{$self->otype} }) {
        $html .= sprintf('<option value="%s"%s>%s</option>' . "\n",
            $_,
            (($values[$count]->{f} || '') eq $_ ? ' selected="on"' : ''),
            $form->attr_label($_),
        );
    }

    $html .= '</select>';
}

sub val_field {
    my ($self, $count) = @_;
    my @values = $self->current_value;
    return sprintf('<input type="text" name="attrval" value="%s">',
        $values[$count]->{v} || '');
}

sub filter {
    my ($self) = @_;
    map { $_->{f} . '~' .  $_->{v} } grep { $_->{f} } $self->current_value;
}

=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;
