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

BEGIN {extends 'Catalyst::Controller'; }

=head1 NAME

LATMOS::Accounts::Web::Controller::Request - Catalyst Controller

=head1 DESCRIPTION

Catalyst Controller.

=head1 METHODS

=cut


=head2 index

=cut

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

}

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

    $obj ||= $c->req->param('obj');

    my $accreq = $c->model('Accounts')->db->get_object('accreq', $form) or do {
        $c->forward('/no_object');
        return;
    };
    
    my $otype = $accreq->get_attributes('oType');
    $c->stash->{accreq} = $accreq;

    if ($accreq->get_attributes('requireObject')) {
        if (!$obj) {
            $c->stash->{ofilter} = $c->model('AttrFilter', $otype);
            $c->stash->{select_object} = 1;
            return;
        } else {
            $c->stash->{object} = $c->model('Accounts')->db->get_object(
                $otype, $obj
            );
        }
    }

    require LATMOS::Accounts::Bases::Sql::DataRequest;
    $c->stash->{datarequest} =
        LATMOS::Accounts::Bases::Sql::DataRequest->new($accreq);
    $c->stash->{datarequest}->set_ptr_object($c->stash->{object})
        if ($c->stash->{object});

    $c->stash->{form} = $c->model(
        'AttrForms',
        '',
        $c->stash->{datarequest},
        $c->model('Accounts')->db
    );

    # Default apply date:
    my @date = localtime( time + 3600 * 24 ); # eg: tomorrow
    $c->stash->{default_apply_date} = sprintf(
        '%02d/%02d/%d',
        $date[3],
        $date[4] + 1,
        $date[5] + 1900
    );

    if ($c->req->param('send')) {
        my %attrs;
        foreach ($c->stash->{datarequest}->attributes) {
            my $htmlname = $c->stash->{form}->attr_field_name($_);
            my @vals = $c->req->param($htmlname);
            $attrs{$_} = @vals > 1 ? \@vals : $vals[0];
        }
        if ($c->stash->{datarequest}->register(
            { user => $c->user->{username},
              apply => $c->req->param('apply') ||
              $c->stash->{default_apply_date} },
            %attrs,
        )) {
            $c->go('recorded');
        }
    }

}

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

    my %attrs = $c->stash->{datarequest}->get_values;
    $c->stash->{values} = \%attrs;
}

=head1 AUTHOR

olivier

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