#!/usr/bin/env perl
# vim: set sw=4 ts=4 et ai si:
#
use strict;
use warnings;

use Getopt::Long;
use Pod::Usage;
use Text::CSV qw(csv);
use WebService::IdoitAPI;

our $VERSION = '0.4.3'; # VERSION

sub get_manufacturers {
    my $api = shift;

    my $req= {
        method => 'cmdb.dialog.read',
        params => {
            category => 'C__CATG__MODEL',
            property => 'manufacturer',
        },
    };
    my $res= $api->request($req);

    unless ( $res) {
        warn "get_manufacturers: $api->{client}->status_line\n";
        return;
    }
    if ( $res->{is_success} ) {
        return $res->{content}->{result};
    }
    else {
        my ($code, $message) = $res->{content}->{error}->@{qw(code message)};
        warn "get_manufacturers: $code: $message";
        return;
    }
} # get_manufacturers()

sub initialize {
    my $config = {};
    my %opt = ();
    my @opt_def = qw(
        config=s csv
        help|?
        json
        man
        pretty
        version
    );
    GetOptions(\%opt, @opt_def);

    pod2usage(-exitstatus => 0, -input => \*DATA)
        if $opt{help};
    pod2usage(-exitstatus => 0, -input => \*DATA, -verbose => 2)
        if $opt{man};
    pod2usage(-exitstatus => 0, -input => \*DATA, -verbose => 99, -sections => 'VERSION')
        if $opt{version};

    $config = WebService::IdoitAPI::read_config($opt{config});

    $config->{opt} = \%opt;

    my $api = WebService::IdoitAPI->new( $config );
    
    $api->login();

    $config->{api} = $api;

    return $config;
} # initialize()

sub print_aoh {
    my ($config,$aoh) = @_;


    if ( $config->{opt}->{json} ) {
        print_aoh_json($config, $aoh);
    }
    elsif ( $config->{opt}->{csv} ) {
        print_aoh_csv($config, $aoh);
    }
    else {
        print_aoh_text($config, $aoh);
    }
} # print_aoh()

sub print_aoh_csv {
    my ($config,$aoh) = @_;

    return unless scalar(@$aoh); # exclude empty array

    my $csv_out = Text::CSV->new({binary => 1, auto_diag => 1});
    my @headers = sort keys %{$aoh->[0]};
    $csv_out->say(\*STDOUT, [@headers]);
    for my $row (@$aoh) {
        $csv_out->say(\*STDOUT, [$row->@{@headers}]);
    }
} # print_aoh_csv()

sub print_aoh_json {
    my ($config,$aoh) = @_;
    my $json = JSON->new();
    $json->canonical();

    if ( $config->{opt}->{pretty} ) {
        print $json->pretty->encode($aoh);
    }
    else {
        print $json->encode($aoh);
    }
} # print_aoh_json()

sub print_aoh_text {
    my ($config,$aoh) = @_;
    print "---------------\n";
    for my $record (@$aoh) {
        for my $key (sort keys %$record) {
            print "$key: $record->{$key}\n";
        }
        print "---------------\n";
    }
} # print_aoh_text()

my $config = initialize();

my $manufacturers = get_manufacturers( $config->{api} );

if ($manufacturers) {
    print_aoh($config, $manufacturers);
}

exit 0;

__END__

=head1 NAME

idoit-manufacturers - get i-doit manufacturers

=head1 VERSION

version 0.4.3

=head1 SYNOPSIS

  idoit-manufacturers [ options ]

  options:
    --config path   - read configuration from file at given path
    --csv           - output as CSV
    --help          - show a short help text and exit
    --json          - output as JSON
    --list          - list manufacturers
    --man           - show the full man page and exit
    --pretty        - show readable JSON output
    --version       - show the version and exit

=head1 OPTIONS AND ARGUMENTS

=head2 Options

=head3 --config path

Read configuration values from a file found at the given path.

This file should contain lines a key and a value
separated by equal sign (I<=>) or colon (I<:>).
The key and the value may be enclosed
in single (I<'>) or double (I<">) quotation marks.
Leading and trailing white space is removed
as well as a comma (I<,>) at the the end of the line.

The program needs the following keys in the file:

=over 4

=item key

The API key for i-doit.

=item url

The URL of the i-doit instance.

=item username

The username for the login (optional).

=item password

The password for the login (optional).

=back

=head3 --help / -?

The program shows a short help text and exits.

=head3 --man

The program shows this man page and exits.

=head3 --csv

The report is printed as CSV.

=head3 --json

The report is printed as JSON.

=head3 --pretty

Given together with option C<< --json >>,
the output is printed as readable formatted JSON.

=head3 --version

The program shows its version and exits.

=head1 AUTHOR

Mathias Weidner C<< mamawe@cpan.org >>

=head1 LICENCE AND COPYRIGHT

Copyright (c) 2023, Mathias Weidner C<< mamawe@cpan.org >>.
All rights reserved.

This software is free software; you can redistribute it and/or
modify it under the same terms as Perl itself. See L<perlartistic>.

=cut
