package LATMOS::Accounts::Bases::Sql::Employment;

use 5.010000;
use strict;
use warnings;

use base qw(LATMOS::Accounts::Bases::Sql::objects);
use LATMOS::Accounts::Log;
use LATMOS::Accounts::I18N;
use Date::Parse;
use DateTime;

our $VERSION = (q$Rev: 594 $ =~ /^Rev: (\d+) /)[0];

=head1 NAME

LATMOS::Accounts::Bases::Sql::Address - Physical office Adress Support

=head1 DESCRIPTION

C<Address> objects allow to store user's several office addresses.

Notice most of other bases (Ldap, ...) support only one address.

=cut

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

    my $user = $self->base->get_object('user', $self->_get_c_field('user'))
        or return $self->id;

    return join(', ', grep { $_ }
        (
            $user,
            $self->get_c_field('firstday'),
        )
    );
}

sub _object_table { 'employment' }

sub _key_field { 'name' }

sub _has_extended_attributes { 1 }

sub _get_attr_schema {
    my ($class, $base) = @_;

    my $attrs = {
        name =>         { inline => 1, },
        exported =>     { inline => 1, },
        user =>         { inline => 1,
            reference => 'user',
            label => l('User'),
        },
        description => {
            label => l('Description'),
        },
        firstday => {
            inline => 1,
            formtype => 'DATE',
            monitored => 1,
            label => l('First day'),
        },
        lastday => {
            inline => 1,
            formtype => 'DATE',
            monitored => 1,
            label => l('Last day'),
        },
        'state' => {
            managed => 1,
            ro => 1,
            get => sub {
                my ($self) = @_;
                my $now = DateTime->now;
                if ($now->epoch < str2time($self->object->get_attributes('firstday'))) {
                    return 1;
                } elsif ( my $end = $self->object->get_attributes('lastday') ) {
                    my $eend = str2time($end) + 86400;
                    if ($now->epoch > $eend) {
                        return -1;
                    }
                } else {
                    return 0;
                }
            },
            label => l('State'),
        },
        contratType => {
            reference => 'group',
            can_values => sub {
                $base->search_objects('group', 'sutype=contrattype')
            },
            monitored => 1,
            label => l('Type of contract'),
        },
        managerContact => {
            delayed => 1,
            can_values => sub {
                my %uniq = map { $_ => 1 } grep { $_ }
                ($_[1] ? $_[1]->get_attributes('managerContact') : ()),
                $base->search_objects('user', 'active=*');
                sort keys %uniq;
            },
            reference => 'user',
            label => l('Contact'),
        },
        department => {
            reference => 'group',
            can_values => sub {
                $base->search_objects('group', 'sutype=dpmt')
            },
            monitored => 1,
            label => l('Department'),
        },
        company => {
            label => l('Company'),
        },
        endcircuit    => {
            formtype => 'DATE',
            monitored => 1,
            label => l('End of entrance'),
        },
        previous => {
            ro => 1,
            managed => 1,
            get => sub {
                my ($self) = @_;
                my $find = $self->object->base->db->prepare_cached(q{
                    SELECT name from employment where "user" = ?
                        and (lastday is not null and lastday < ?)
                        order by lastday desc
                });
                $find->execute(
                    $self->object->get_field('user'),
                    $self->object->get_field('firstday')
                );
                my $res = $find->fetchrow_hashref;
                $find->finish;
                return $res->{name};
            },
            label => l('Previous'),
        },
        next => {
            ro => 1,
            managed => 1,
            get => sub {
                my ($self) = @_;
                my $find = $self->object->base->db->prepare_cached(q{
                    SELECT name from employment where "user" = ?
                        and firstday > ?
                        order by firstday asc
                });
                $find->execute(
                    $self->object->get_field('user'),
                    $self->object->get_field('lastday')
                );
                my $res = $find->fetchrow_hashref;
                $find->finish;
                return $res->{name};
            },
            label => l('Next'),
        },
        minFirstDay => {
            ro => 1,
            hidden => 1,
            managed => 1,
            formtype => 'DATE',
            get => sub {
                my ($attr) = @_;
                my $self = $attr->object;

                my $find = $self->base->db->prepare_cached(q{
                    SELECT max(lastday) as lastday FROM employment where "user" = ?
                        and lastday is not NULL and lastday < ?
                    });

                my $first = $self->get_field('firstday');

                $find->execute(
                    $self->get_field('user'),
                    $first
                );
                my $res = $find->fetchrow_hashref;
                $find->finish;

                if ($res && $res->{lastday}) {
                    my $dt = DateTime->from_epoch( epoch => str2time($res->{lastday}));
                    $dt->set_time_zone( DateTime::TimeZone->new( name => 'local' ) );
                    $dt->add(days => 1);
                    if ($first eq $dt->ymd('-')) {
                        return $first;
                    } else {
                        return $dt->ymd('-');
                    }
                } else {
                    return;
                }
            },
            label => l('Minimal first day'),
        },
        maxLastDay => {
            ro => 1,
            hidden => 1,
            managed => 1,
            formtype => 'DATE',
            get => sub {
                my ($attr) = @_;
                my $self = $attr->object;

                my $find = $self->base->db->prepare_cached(q{
                    SELECT min(firstday) as firstday FROM employment where "user" = ?
                        and firstday > ?
                    });

                my $last = $self->get_field('lastday') or do {
                    # This contract is last then...
                    return;
                };

                $find->execute(
                    $self->get_field('user'),
                    $last
                );
                my $res = $find->fetchrow_hashref;
                $find->finish;

                if ($res && $res->{firstday}) {
                    my $dt = DateTime->from_epoch( epoch => str2time($res->{firstday}));
                    $dt->set_time_zone( DateTime::TimeZone->new( name => 'local' ) );
                    $dt->subtract(days => 1);
                    if ($last eq $dt->ymd('-')) {
                        return $last;
                    } else {
                        return $dt->ymd('-');
                    }
                } else {
                    return;
                }
            },
            label => l('Maximal last day'),
        },
    };

    # Completed contract are RO, we allow to still set lastday
    foreach (qw(endcircuit firstday contratType department managerContact company)) {
        $attrs->{$_}{ro} = sub {
            my ($self) = $_[0];
            $self or return 0;
            return $self->get_attributes('state') < 0 ? 1 : 0;
        };
    }
    $class->SUPER::_get_attr_schema($base, $attrs);
}

sub _create {
    my ($class, $base, $id, %data) = @_;
    $data{user} or return;
    my $user = $base->get_object('user', $data{user});
    $user or return;
    $class->SUPER::_create($base, $id, %data);
}

=head2 applyToUser()

Set user's attributes if need from this employement.

=cut

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

    my $user = $self->base->get_object('user', $self->get_attributes('user')) or do {
        $self->base->log(LA_ERR, "Cannot fetch user %s to apply employment", $self->get_attributes('user'));
        return;
    };

    my $currentemployment = $user->get_attributes('currentEmployment') || '';

    my $expire = str2time($user->get_attributes('expire') || '1970-01-01T00:00:00');

    my %changes;
    foreach (qw( endEmployment endStrictEmployment endCurrentEmployment endLastEmployment )) {
        my $old = $user->_get_attributes($_) || '';
        my $new = $user->_get_attributes("_$_") || '';
        if ($old ne $new) {
            $changes{$_} = $new;
        }
    }

    # If there is no current employment we try to find any to not let expire
    # unset
    my $endemploy = $currentemployment
        ? $user->_get_attributes('_endEmployment')
        : $user->_get_attributes('_endLastEmployment');
    my $nextexpire = str2time($endemploy || '1970-01-01T00:00:00');

    if ($expire != $nextexpire) {
        $changes{expire} = $endemploy;
    }

    if (keys %changes) {
        $user->ReportChange('Update', 'Update %s to match employment', join(', ', sort keys %changes));
        $user->ReportChange('Update', 'Expire update to %s to match employment', ($endemploy || '(none)'))
            if (exists($changes{expire}));
        $user->set_fields(%changes);
    }

    if ($currentemployment ne $self->id) {
        # No sync to do if this employment is not currently applied
        return;
    }

    my %attrsets = (
        appliedEmployement => $self->id,
    );
    foreach my $attr (qw(company contratType department managerContact endcircuit)) {
        my $uval = $user->get_attributes($attr) || '';
        my $cval = $self->get_attributes($attr) || '';

        if ($uval ne $cval) {
            my $oattr = $self->base->attribute('user', $attr);
            $attrsets{$oattr->iname} = $cval;
        }
    }

    if (keys %attrsets) {
        if (my $res = $user->set_fields(%attrsets)) {
            $user->ReportChange('Update', 'Attr %s updated to match Employment %s', join(', ', sort keys %attrsets), $self->id);
            return $res;
        }
    } else {
        return 1;
    }
}

sub checkValues {
    my ($class, $base, $obj, %changes) = @_;

    my $user = $changes{user} || $obj->get_attributes('user');
    my $id = ref $obj ? $obj->id : $obj;

    if ($changes{lastday}) {
        my $sth = $base->db->prepare_cached(q{
            select name from employment where "user" = ? and name != ? and
                firstday <= ? and (lastday is null or lastday >= ?)
        });
        $sth->execute($user, $id, $changes{lastday}, $changes{lastday});
        my $res = $sth->fetchrow_hashref;
        $sth->finish;
        if ($res) {
            $base->log(LA_ERR, "New ending overlap contrat %s (%s)", $res->{name}, $changes{lastday});
            return;
        }
    } elsif(exists($changes{lastday})) {
        my $sth = $base->db->prepare_cached(q{
            select * from employment where "user" = ? and lastday is null
            limit 1
        });
        $sth->execute($user);
        my $res = $sth->fetchrow_hashref;
        if ($res && $res->{name}) {
            if ($id ne $res->{name}) {
                $base->log(LA_ERR, "Another contract has no ending (%s)", $res->{name} || '');
                return;
            }
        }
    }
    if ($changes{firstday}) {
        my $sth = $base->db->prepare_cached(q{
            select name from employment where "user" = ? and name != ? and
                firstday <= ? and (lastday is null or lastday >= ?)
        });
        $sth->execute($user, $id, $changes{firstday}, $changes{firstday});
        my $res = $sth->fetchrow_hashref;
        $sth->finish;
        if ($res) {
            $base->log(LA_ERR, "New starting overlap contrat %s (%s)", $res->{name}, $changes{firstday});
            return;
        }
    }


    return 1;
}

sub ReportChange {
    my ($self, $changetype, $message, @args) = @_;

    $self->applyToUser();

    $self->SUPER::ReportChange($changetype, $message, @args);
}

1;

__END__

=head1 SEE ALSO

L<LATMOS::Accounts::Bases::Sql>

=head1 AUTHOR

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

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2008, 2009 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
