#!/usr/bin/perl

use strict;
use warnings;
use LATMOS::Accounts;
use LATMOS::Accounts::Utils;
use Getopt::Long;
use Pod::Usage;
use LATMOS::Accounts::I18N;

=head1 NAME

    la-load-csv - Create object from CSV file

=head1 SYNOPSIS

    la-load-csv Input.csv 

=head1 DESCRIPTION

=cut

GetOptions(
    'c|config=s'        => \my $config,
    'b|base=s'          => \my $base,
    'o|object=s'        => \my $otype,
    't|test'            => \my $test,
    'help'              => sub { pod2usage(0) },
) or pod2usage();

$otype ||= 'user';

=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 -o|object object_type

Query will be performed on this object. Default is the 'User' object.

=item -t|--test

If the underlying database support it don't commit change at the end (Works
only on SQL base currently)

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

unless ($labase->is_supported_object($otype)) {
    die "Unsupported object type `$otype'\n";
}

open(my $fh, '<', $ARGV[0]) or die "Cannot open  $ARGV[0]: $!\n";

loadCSV(
    $fh,
    cb => sub {
        my ($res, $linecount) = @_;

        my $ochelper = $labase->ochelper($otype);
       
        my $info = {
            contents => $res
        };
        if ($res->{name}) {
            $info->{name}{content} = $res->{name};
        }
        
        $ochelper->Automate($info) or
            die "Cannot create object line $linecount (not enough information ?)\n";
    },
);

if($test) {
    warn "Changes not commited due to test option\n";
} else {
    $labase->commit();
}
