package LATMOS::Accounts::Task::Employment;

use strict;
use warnings;
use base qw(LATMOS::Accounts::Task);
use LATMOS::Accounts;
use LATMOS::Accounts::Log;
use LATMOS::Accounts::Utils;
use LATMOS::Accounts::Bases::Sql::Employment;

=head1 NAME

LATMOS::Accounts::Task::Stats - Store value to perform some statistics

=head1 DESCRIPTION

=cut

sub init {
    my ($self) = @_;
    my $LA = LATMOS::Accounts->new($self->{config}, noacl => 1);
    my $labase = $self->{base} ? $LA->base($self->{base}) : $LA->base;
    $labase && $labase->load or die "Cannot load base";

    $self->{_la} = $LA;
    $self->{_base} = $labase;

    1;
}

sub needupd { 1 }

sub run {
    my ($self) = @_;

    my %users = map { $_ => undef } $self->{_base}->search_objects('user', 'exported=true');
    my %old = $self->{_base}->attributes_summary_by_object('user', 'appliedEmployement');
    foreach (keys %old) {
        exists($users{$_}) or next;
        $users{$_} = $old{$_}->[0] || '';
    }

    my $listempl = $self->{_base}->db->prepare_cached(q{
        SELECT * FROM employment where firstday <= now() and (lastday is null or lastday >= now() - '1 days'::interval)
            and exported = true
            order by lastday, firstday
    });
    $listempl->execute();
    my %new  = ();
    while (my $res = $listempl->fetchrow_hashref) {
        my $employment = $res->{name};
        my $user = $res->{user};
        if ($employment ne $users{$user}) {
            $self->{_base}->log(LA_NOTICE, "Updating user $user to match employment `%s'", $employment || '');
            my $ouser = $self->{_base}->get_object('user', $user) or next;

            my $job = $self->{_base}->get_object('employment', $employment);
            $job->applyToUser;
            $self->{_base}->commit;
        }
        delete($users{$user});
    }

    # Change has old employment => nothing
    # if user is still active, expired account remains untouched
    foreach my $user ($self->{_base}->search_objects('user', 'active=1')) {
        if ($users{$user}) {
            my $ouser = $self->{_base}->get_object('user', $user);
            my %changes = (
                appliedEmployement => undef,
            );
            foreach my $attr (LATMOS::Accounts::Bases::Sql::Employment::_reported_atributes) {
                my $default = $self->{_base}->config("unemployment.$attr") || '';
                my $old = $ouser->_get_attributes($attr) || '';
                if ($old ne $default) {
                    $changes{$attr} = $default || undef;
                }
            }
            if ($ouser->set_fields(%changes)) {
                $self->{_base}->log(LA_NOTICE, "Updating user $user to match unemployment");
                $ouser->ReportChange('Update', 'Update %s to match unemployment', join(', ', sort keys %changes));
                $self->{_base}->commit;
            } else {
                $self->{_base}->rollback;
            }
        }
    }

    return 1;
}

1;

__END__

=head1 SEE ALSO

L<LATMOS::Accounts>, L<LATMOS::Accounts::Task>

=head1 AUTHOR

Olivier Thauvin, E<lt>olivier.thauvin@latmos.ipsl.frE<gt>

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2012 CNRS SA/CETP/LATMOS

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.10.0 or,
at your option, any later version of Perl 5 you may have available.

=cut

