#!/usr/bin/perl

use strict;
use warnings;
use LATMOS::Accounts;
use Getopt::Long;
use Pod::Usage;
use LATMOS::Accounts::I18N;
use Date::Parse;
use DateTime;

=head1 NAME

    la-query - Tools to query base in LATMOS::Accounts system

=head1 SYNOPSIS

    la-query [options] [obj_id]

=head1 DESCRIPTION

[obj_id] : If present, all set attributes (rw) will be displayed for that obj_id.
        If none is given, all obj_ids will be printed.

For the default object_type (user), obj_id = login.

Example : la-query lambda

=cut

GetOptions(
    'c|config=s'        => \my $config,
    'b|base=s'          => \my $base,
    'd=i'               => \my $delay,
    'help'              => sub { pod2usage(0) },
) or pod2usage();

my $otype = 'user';
$delay ||= 60; # Jours

=head1 OPTIONS

=over 4

=item -c|--config configdir

Use this configuration directory instead of the default one.

=item -b|--base basename

Query this specific base instead of the default one.

=item -d days

The delay for new employment in days

=back

=cut

my $LA = LATMOS::Accounts->new($config, noacl => 1);
my $labase = $LA->base($base);
$labase && $labase->load or die l("Cannot load base %s\n", $base);

$labase->unexported(0);

foreach my $user (@ARGV) {
    my $ouser = $labase->get_object($otype, $user) or die "Cannot find user $user\n";

    my @employements = $ouser->listEmployment;

    my $lastemp = $employements[0] or do {
        warn "$user has no employment\n";
        next;
    };

    my $oemp = $labase->get_object('employment', $lastemp);

    my $lastday = $oemp->get_attributes('lastday') or do {
        warn "$user has unlimited employement\n";
        next;
    };

    my %newvalues = ( user => $user );
    foreach (qw(company managerContact contratType department)) {
        $newvalues{$_} = $oemp->get_attributes($_);
    }
    my $time = DateTime->from_epoch(epoch => str2time($lastday));
    $time->set_time_zone( DateTime::TimeZone->new( name => 'local' ) );
    $time->add( days => 1 );
    $newvalues{firstday} = $time->ymd('-');
    my $name = "$user-$newvalues{firstday}";
    $time->add( days => $delay );
    $newvalues{lastday} = $time->ymd('-');

    $labase->create_object('employment', $name, %newvalues);

    print "$user: new end $newvalues{lastday} ($newvalues{contratType})\n";
    $labase->commit;
}

