#!/usr/bin/perl

use strict;
use warnings;
use LATMOS::Accounts;
use Getopt::Long;
use Pod::Usage;
use Spreadsheet::WriteExcel;

=head1 NAME

    la2xls - Output data in XLS format

=head1 SYNOPSIS

    la-search [options] filter [filter2 [...]] [attributes [...]]

=head1 OPTIONS

=over 4

=item --config configdir

Use this configuration directory instead default

=item --base basename

Perform search in this specific base instead default

=item --with-unexp

Take into account all objects (even non propagated ones, with attribute
'exported'=0) (default)

=item --wo-unexp

Take into account only propagated objects (attribute 'exported'=1)

=item -f FILE

The output filename. The default is la2xls.xls.

=item FILTER

Filter are in form "[ATTRIBUTE][OPERATOR][VALUE]"

where attribute is a supported attribute.

OPERATOR can be:

=over 4

=item C<=>

Search object having attribute strictely equal to VALUE. If VALUE is C<*> match
any non empty value.

=item C<~>

Search object having attribute containing VALUE.

=back

=back

=cut

GetOptions(
    'c|config=s'        => \my $config,
    'b|base=s'          => \my $base,
    'o|object=s'        => \my $otype,
    'no-unexp|wo-unexp' => \my $nounexp,
    'with-unexp'        => \my $unexp,
    'f|file=s'          => \my $file,
    'help'              => sub { pod2usage(0) },
) or pod2usage();

if (!$ARGV[0]) {warn "You must specify 'filter', aborting\n"; pod2usage(); }

$otype ||= 'user';
$file  ||= 'la2xls.xls';

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

$labase->unexported($nounexp ? 0 : 1);

my (@filters, @attr);

foreach (@ARGV) {
    if (/(~|=)/) {
        push(@filters, $_);
    } else {
        push(@attr, $_);
    }
}

my @result = $labase->search_objects($otype, @filters);

my @objs = map { $labase->get_object($otype, $_) } @result;

# Create a new Excel workbook
my $workbook = Spreadsheet::WriteExcel->new($file);

# Add a worksheet
my $worksheet = $workbook->add_worksheet();

#  Add and define a format
my $format = $workbook->add_format(); # Add a format
$format->set_bold();
$format->set_align('center');

$worksheet->write(0, 0, 'name', $format);
my $row = 0;
foreach my $obj (@objs) {
    $row++;
    $worksheet->write($row, 0, $obj->id);
}



foreach my $col (0 .. $#attr) {
    $worksheet->write(0, $col+1, $attr[$col], $format);

    my $row = 0;
    foreach my $obj (@objs) {
        $row++;
        $worksheet->write($row, $col+1, $obj->get_attributes($attr[$col]));
    }
}

$workbook->close();
