package LATMOS::Accounts::Web::Controller::Create;

use strict;
use warnings;
use base 'Catalyst::Controller';
use LATMOS::Accounts::Utils;
use LATMOS::Accounts::Log;

=head1 NAME

LATMOS::Accounts::Web::Controller::Create - Catalyst Controller

=head1 DESCRIPTION

Catalyst Controller.

=head1 METHODS

=cut


=head2 index 

=cut

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

    $c->response->body('Matched LATMOS::Accounts::Web::Controller::Create in Create.');
}

sub default : LocalPath {
    my ($self, $c, undef, $otype ) = @_;
    my $base = $c->model('Accounts')->db;
    my ($step) = $c->req->param('step');
    my $form = $c->model('AttrForms', undef, $otype, $base);
    my ($status, $info);
    $c->stash->{page}{title} = "Ajouter un objet / $otype";
    if ($step) {
        $info = $c->session->{ochelper};
    }
    if ($info->{name}{ask}) {
        $info->{name}{content} = $c->req->param('_name');
    }
    foreach my $attr (@{$info->{ask} || []}) {
        my $field = $form->field($attr);
        my @vals = grep { $_ } $c->req->param($field->attr_field_name());
        $info->{contents}{$attr} = @vals > 1 ? \@vals : $vals[0]
            if (@vals);
    }
    my $ochelper = $base->ochelper($otype);
    ($status, $info) = $ochelper->step($info);
    
    if ($status eq 'CREATED') {
        $base->commit;
        $c->res->redirect($c->uri_for('/',
                $c->forward('/obj_to_uri', [ $otype ]),
                $info->{name}{content}));
    } elsif ($status eq 'ERROR') {
        # On error, restart the process
        $c->stash->{page}{error} =
            'Erreur lors de la création de l\'objet: ' .
            LATMOS::Accounts::Log::lastmessage(LA_ERR);
        $base->rollback;
        foreach my $attr (@{$info->{ask} || []}) {
            my $field = $form->field($attr);
            $c->req->params->{$field->attr_field_name()} = $info->{contents}{$attr};
        }
        $info->{step} = 0; # reset
        ($status, $info) = $ochelper->step($info);
    } else {
        foreach my $attr (@{$info->{ask} || []}) {
            my $field = $form->field($attr);
            $c->req->params->{$field->attr_field_name()} = $info->{contents}{$attr};
        }
        $base->rollback;
    }
    $c->stash->{form} = $form;
    $c->stash->{ochelper} = $info; 
    $c->session->{ochelper} = $info;
}


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