# +==========================================================================+
# || CipUX::Object::Client                                                  ||
# ||                                                                        ||
# || CipUX Object Client                                                    ||
# ||                                                                        ||
# || Copyright (C) 2008 - 2009 by Christian Kuelker. All rights reserved!   ||
# ||                                                                        ||
# || License: GNU General Public License - GNU GPL version 2                ||
# ||          or (at your opinion) any later version.                       ||
# ||                                                                        ||
# +==========================================================================+
# ID:       $Id: Client.pm 5011 2010-07-30 23:31:16Z christian-guest $
# Revision: $Revision: 5011 $
# Head URL: $HeadURL$
# Date:     $Date: 2010-07-31 01:31:16 +0200 (Sat, 31 Jul 2010) $
# Source:   $Source$

package CipUX::Object::Client;

use 5.008001;
use strict;
use warnings;

use Carp;
use Class::Std;
use CipUX::Object::Action::Create;
use CipUX::Object::Action::Destroy;
use CipUX::Object::Action::List;
use Data::Dumper;
use English qw( -no_match_vars);
use Getopt::Long;    # command line options
use Log::Log4perl qw(:easy);
use Pod::Usage;
use Readonly;
use base qw(CipUX::Object::Action);

{                    # BEGIN INSIDE-OUT CLASS

    use version; our $VERSION = qv('3.4.0.5');
    use re 'taint';    # Keep data captured by parens tainted
    delete @ENV{qw(PATH IFS CDPATH ENV BASH_ENV)};    # Make %ENV safe

    # +======================================================================+
    # || CONSTANTS                                                          ||
    # +======================================================================+
    Readonly::Scalar my $EMPTY_STRING => q{};
    Readonly::Scalar my $LINEWIDTH    => 78;
    Readonly::Scalar my $L4PCONF      => '/etc/cipux/log4perl.conf';

    Readonly::Array my @ACTION => qw( list create destroy);

    # +======================================================================+
    # || INIT ARGS                                                          ||
    # +======================================================================+

    # register client with name:
    #     name : cipux_object_client
    my %name_of : ATTR( init_arg => 'name');

    # +======================================================================+
    # || GLOBALS                                                            ||
    # +======================================================================+
    my $L = q{=} x $LINEWIDTH;
    $L .= "\n";
    my $mattrvalue_hr = {};
    my %opt           = ();
    my $script        = $EMPTY_STRING;
    my %option        = (

        'cipux_object_client' => {
            'must' => [qw(a=action)],
            'may'  => [
                qw(c cfg D debug h ? help p pretty V verbose version x mattrvalue t type o object)
            ],
            'not' => [],
        },

        'list' => {
            'must' => [qw()],
            'may' => [qw(c cfg D debug h ? help p pretty V verbose version )],
            'not' => [qw(x mattrvalue t type o object)],
        },

        'create' => {
            'must' => [qw(t=type o=object)],
            'may' =>
                [qw(c cfg D debug h ? help mattrvalue V verbose version x)],
            'not' => [qw(p pretty)],
        },

        'destroy' => {
            'must' => [qw(t=type o=object)],
            'may'  => [qw(c cfg D debug h ? help V verbose version )],
            'not'  => [qw(p pretty x mattrvalue)],
        },
    );

    sub run {

        # +------------------------------------------------------------------+
        # | API
        my ( $self, $arg_r ) = @_;

        # constructor parameter from CipUX::Object::Client
        my $script = $name_of{ ident $self};

        # test right away if we have a valid name
        if ( $script ne 'cipux_object_client' ) {
            $self->exc( { msg => 'unknown script name', value => $script } );
        }

        # +------------------------------------------------------------------+
        # | Environment
        Getopt::Long::Configure('bundling');

        GetOptions(
            \%opt,
            'action|a=s',
            'cfg|c=s',
            'debug|D',
            'help|h',
            'object|o=s',
            'pretty|p',
            'type|t=s',
            'version|V',
            'verbose',
            'mattrvalue|x=s%' =>
                sub { $self->store_mattrvalue( $mattrvalue_hr, \%opt, @_ ); },
            )
            or pod2usage(
            -exitstatus => 2,
            -msg        => "$L problems parsing command line!\n$L"
            );

        if ( exists $opt{debug} ) {
            Log::Log4perl->init_once($L4PCONF);
        }

        my $logger = get_logger(__PACKAGE__);
        $logger->debug('SUB');

        # display help page
        if ( exists $opt{help} ) {
            pod2usage( -exitstatus => 0, -verbose => 1 );
        }

        if ( exists $opt{version} ) {
            $self->out("$script $VERSION\n");
            exit 0;
        }

        my $run_action = exists $opt{action} ? $opt{action} : undef;

        if ( not defined $run_action ) {
            my $msg = "$L Please give parameter --action or -a! \n";
            $msg .= "valid object actions are: \n";
            foreach my $a (@ACTION) {
                $msg .= "$a\n";
            }
            $msg .= $L;
            pod2usage( -exitstatus => 1, -verbose => 0, -msg => $msg );
        }
        $logger->debug( 'run_action: ', $run_action );

        my $ret = $self->test_cli_option(
            {
                script   => $run_action,
                logic_hr => \%option,
                opt_hr   => \%opt,
                debug    => 0,
            }
        );

        # +------------------------------------------------------------------+
        # | main

        my $action
            = exists $opt{action}
            ? $opt{action}
            : undef;

        my $pretty
            = exists $opt{pretty}
            ? 1
            : 0;

        my $object
            = exists $opt{object}
            ? $opt{object}
            : undef;

        my $type
            = exists $opt{type}
            ? $opt{type}
            : undef;

        my $cfg
            = exists $opt{cfg}
            ? $opt{cfg}
            : undef;

        $logger->debug( 'pretty: ', $pretty );
        if ( defined $object ) {
            $logger->debug( 'object: ', $object );
        }
        if ( defined $type ) {
            $logger->debug( 'type: ', $type );
        }
        if ( defined $cfg ) {
            $logger->debug( 'cfg: ', $cfg );
        }

        if ( scalar( grep { $_ eq $action } @ACTION ) < 1 ) {
            my $msg = "unknown object action [$action]\n";

            $msg .= "valid object actions are: \n";
            foreach my $a (@ACTION) {
                $msg .= "$a\n";
            }
            $msg .= $L;
            $self->exc( { msg => $msg } );
        }

        my $sub = 'cipux_object_' . $run_action;
        $self->$sub(
            {
                action        => $action,
                pretty        => $pretty,
                type          => $type,
                object        => $object,
                cfg           => $cfg,
                mattrvalue_hr => $mattrvalue_hr,
            }
        );

        return;
    }

    # +----------------------------------------------------------------------+
    # | cipux_object_list                                                    |
    # +----------------------------------------------------------------------+
    sub cipux_object_list {

        # +------------------------------------------------------------------+
        # | API
        my ( $self, $arg_r ) = @_;
        my $cfg
            = exists $arg_r->{cfg}
            ? $self->l( $arg_r->{cfg} )
            : $self->perr('cfg');

        my $pretty
            = exists $arg_r->{pretty}
            ? $self->l( $arg_r->{pretty} )
            : $self->perr('pretty');

        #foreach my $p (qw(cfg)) {
        #    if ( not defined $arg_r->{$p} ) {
        #        my $msg = 'parameter not defined in sub cipux_object_list';
        #        $self->exc( { msg => $msg, value => $p } );
        #    }
        #}

        # +------------------------------------------------------------------+
        # | main
        my $logger = get_logger(__PACKAGE__);
        $logger->debug('SUB  cipux_object_list');
        $logger->debug( 'pretty: ', $pretty );
        $logger->debug( 'cfg: ', { filter => \&Dumper, value => $cfg } );

        $self->_print_list_type( { pretty => $pretty, cfg => $cfg } );

        # +------------------------------------------------------------------+
        # | API
        return;
    }

    # +----------------------------------------------------------------------+
    # | cipux_object_create                                                  |
    # +----------------------------------------------------------------------+
    sub cipux_object_create {

        # +------------------------------------------------------------------+
        # | API
        my ( $self, $arg_r ) = @_;

        my $type
            = exists $arg_r->{type}
            ? $self->l( $arg_r->{type} )
            : $self->perr('type');

        my $object
            = exists $arg_r->{object}
            ? $self->l( $arg_r->{object} )
            : $self->perr('object');

        my $cfg
            = exists $arg_r->{cfg}
            ? $self->l( $arg_r->{cfg} )
            : $self->perr('cfg');

        my $mattrvalue_hr
            = exists $arg_r->{mattrvalue_hr}
            ? $self->h( $arg_r->{mattrvalue_hr} )
            : $self->perr('mattrvalue_hr');

        foreach my $p (qw(type object)) {
            if ( not defined $arg_r->{$p} ) {
                my $msg = 'parameter not defined in sub cipux_object_create';
                $self->exc( { msg => $msg, value => $p } );
            }
        }

        # +------------------------------------------------------------------+
        # | main
        my $logger = get_logger(__PACKAGE__);

        my $cfg_coupling_hr = $self->get_coupling_cfg();
        my $cfg_object_hr   = $self->get_object_cfg();
        my $cfg_basis_hr    = $self->get_basis_cfg();

        my $create = CipUX::Object::Action::Create->new( { cfg => $cfg } );

        my $return = $create->create_object_action(

            {
                action  => 'create_object_action',
                type    => $type,
                object  => $object,
                attr_hr => $mattrvalue_hr,

           #overwrite_hr => $overwrite_hr, # TODO define that in CipUX::Object
            }
        );

        # +------------------------------------------------------------------+
        # | API
        return $return;

    }

    sub cipux_object_destroy {

        # +------------------------------------------------------------------+
        # | API
        my ( $self, $arg_r ) = @_;

        my $type
            = exists $arg_r->{type}
            ? $self->l( $arg_r->{type} )
            : $self->perr('type');

        my $object
            = exists $arg_r->{object}
            ? $self->l( $arg_r->{object} )
            : $self->perr('object');

        my $cfg
            = exists $arg_r->{cfg}
            ? $self->l( $arg_r->{cfg} )
            : $self->perr('cfg');

        foreach my $p (qw(type object )) {
            if ( not defined $arg_r->{$p} ) {
                my $msg = 'parameter not defined in sub cipux_object_destroy';
                $self->exc( { msg => $msg, value => $p } );
            }
        }

        # +------------------------------------------------------------------+
        # | main
        my $logger = get_logger(__PACKAGE__);
        $logger->debug( 'object: ', $object );
        $logger->debug( 'type: ',   $type );

        my $cfg_coupling_hr = $self->get_coupling_cfg();
        my $cfg_object_hr   = $self->get_object_cfg();
        my $cfg_basis_hr    = $self->get_basis_cfg();

        $logger->debug(
            'cfg_coupling_hr',
            {
                filter => \&Dumper,
                value  => $cfg_coupling_hr
            }
        );

        my $destroy = CipUX::Object::Action::Destroy->new(
            {
                cfg_coupling_hr => $cfg_coupling_hr,
                cfg_object_hr   => $cfg_object_hr,
                cfg_basis_hr    => $cfg_basis_hr
            }
        );
        my $return = $destroy->destroy_object_action(
            {
                action => 'destroy_object_action',
                type   => $type,
                object => $object,
            }
        );

        # +------------------------------------------------------------------+
        # | API
        return 1;
    }

    # +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+
    # | PRIVATE INTERFACE                                                    |
    # +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+

    sub _print_list_type {

        # +------------------------------------------------------------------+
        # | API
        my ( $self, $arg_r ) = @_;
        my $pretty
            = exists $arg_r->{pretty} ? $self->l( $arg_r->{pretty} ) : 0;
        my $cfg = exists $arg_r->{cfg} ? $self->l( $arg_r->{cfg} ) : 0;

        my $logger = get_logger(__PACKAGE__);
        $logger->debug( 'pretty: ', $pretty );
        $logger->debug( 'cfg: ',    $cfg );

        my $cfg_coupling_hr = $self->get_coupling_cfg();
        my $cfg_object_hr   = $self->get_object_cfg();
        my $cfg_basis_hr    = $self->get_basis_cfg();

        $logger->debug(
            'cfg_coupling_hr: ',
            {
                filter => \&Dumper,
                value  => $cfg_coupling_hr
            }
        );

        my $list_ar
            = $self->list_type( { cfg_coupling_hr => $cfg_coupling_hr } );

        $logger->debug(
            'list_ar',
            {
                filter => \&Dumper,
                value  => $list_ar
            }
        );

        # this is without pretty print!
        #
        # foreach my $line (@$list_ar){
        #     chomp($line);
        #     $self->out( "$line\n");
        # }

        # mostly this stuff is for pretty print
        my $max_col = 0;
        my $width   = 0;

        if ($pretty) {
            foreach my $line ( @{$list_ar} ) {
                if ( $max_col < length $line ) { $max_col = length $line; }
            }
            $width = 2 + $max_col;
            $self->out( q{+} . q{-} x $width . "+\n" );
            $self->out( sprintf '| %-' . $max_col . "s |\n", 'type' );
            $self->out( q{+} . q{=} x $width . "+\n" );
        }

        foreach my $line ( @{$list_ar} ) {
            chomp $line;
            if ($pretty) {
                $self->out( sprintf '| %-' . $max_col . "s |\n", $line );
            }
            else {
                $self->out("$line\n");
            }
        }

        if ($pretty) { $self->out( q{+} . q{-} x $width . "+\n" ); }

        # +------------------------------------------------------------------+
        # | API
        return;

    }

    # +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+
    # | PUBLIC INTERFACE                                                     |
    # +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+
    sub DEMOLISH {

        # +------------------------------------------------------------------+
        # | API
        my ($self) = @_;

        # actualize library information
        #Library->remove($self);

        # +------------------------------------------------------------------+
        # | API
        return;

    }

    # +======================================================================+
    # || METHODS                                                            ||
    # +======================================================================+

}    # END INSIDE-OUT CLASS

1;   # Magic true value required at end of module

__END__

=head1 NAME

CipUX::Object::Client - Command line client for CipUX objects


=head1 VERSION

This document describes CipUX::Object::Client version 3.4.0.5


=head1 SYNOPSIS

 use CipUX::Object::Client;

 my $c = CipUX::Object::Client->new({name=>'cipux_object_client'});

 $c->run();

=head1 DESCRIPTION

Command line client library for CipUX Object.


=head1 SUBROUTINES/METHODS

=head2 DEMOLISH

TODO

=head2 run

TODO

=head2 cipux_object_create

TODO

=head2 cipux_object_destroy

TODO

=head2 cipux_object_list

TODO

=head1 DIAGNOSTICS

=for author to fill in:
    List every single error and warning message that the module can
    generate (even the ones that will "never happen"), with a full
    explanation of each problem, one or more likely causes, and any
    suggested remedies.

=over

=item C<< Error message here, perhaps with %s placeholders >>

[Description of error here]

=item C<< Another error message here >>

[Description of error here]

[Et cetera, et cetera]

=back


=head1 CONFIGURATION AND ENVIRONMENT

CipUX::Object::Client requires no configuration files or environment variables.


=head1 DEPENDENCIES

TODO

=head1 INCOMPATIBILITIES

None reported.


=head1 BUGS AND LIMITATIONS

No bugs have been reported.


=head1 SEE ALSO

See the CipUX webpage and the manual at L<http://www.cipux.org>


=head1 AUTHOR

Christian Kuelker  C<< <christian.kuelker@cipworx.org> >>


=head1 LICENSE AND COPYRIGHT

Copyright (C) 2008 - 2009 , Christian Kuelker. All rights reserved.

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2, or (at
your option) any later version.

This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA


=head1 DISCLAIMER OF WARRANTY

BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
NECESSARY SERVICING, REPAIR, OR CORRECTION.

IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE
LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL,
OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE
THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

=cut
