# +========================================================================+
# || Copyright (C) 2006 - 2009 Christian Kuelker                          ||
# ||                                                                      ||
# || License: GNU General Public License - GNU GPL - version 2            ||
# ||          or (at your opinion) any later version                      ||
# +========================================================================+
#  ID:       $Id$
#  Revision: $Revision$
#  Head URL: $HeadURL$
#  Date:     $Date$
#  Source:   $Source$

package CipUX::CAT::Web::Module::ModuleSwitch;

use warnings;
use strict;
use Data::Dumper;
use Log::Log4perl qw(get_logger :levels);
use base qw(CipUX::CAT::Web::Module);

{

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

    # CONST
    Readonly::Scalar my $EMPTY_STRING => q{};

    # name of the module or module array
    Readonly::Scalar my $NAME   => 'module_switch';
    Readonly::Scalar my $MODULE => 'module_switch.cgi';
    Readonly::Scalar my $ICON   => 'module.png';

    # task to be registerd for this module.
    Readonly::Array my @TASK => qw(
        cipux_task_retrieve_all_cat_module_name_shortdescription_templatedir_author_version_license_isenabled_icon
    );

    sub register {

        my $self = shift;

        # provide a name
        $self->set_module_name_register(
            { class => __PACKAGE__, name => $MODULE } );
        my $cfg_ar = $self->module_cfg;
        $self->set_module_cfg_register(
            { cfg_ar => $cfg_ar, name => $MODULE } );

        return 1;
    }

    # This will called last, because of base first
    sub module_cfg : CUMULATIVE(BASE FIRST) {

        my $self = shift;

        my $trans_name = $NAME;
        $trans_name =~ s{_}{ }gmx;
        my $desc = 'This module can be used to enable or';
        $desc .= ' disable CipUX CAT Web modules.';
        my $module_hr = {};
        $module_hr->{cipuxName}             = $trans_name;
        $module_hr->{cipuxTemplateDir}      = $NAME;
        $module_hr->{cipuxIcon}             = $ICON;
        $module_hr->{cipuxDescription}      = $desc;
        $module_hr->{cipuxShortDescription} = 'Switch on/off modules';
        $module_hr->{cipuxTask}             = \@TASK;

        return [$module_hr];
    }

    # this is the subroutine which trigger the module output
    sub module {

        my ( $self, $arg_r ) = @_;
        my $cmd = $TASK[0];
        my $rpc
            = ( exists $arg_r->{rpc_obj} )
            ? $arg_r->{rpc_obj}
            : $self->perr('rpc_obj');
        my $cgi
            = ( exists $arg_r->{cgi_obj} )
            ? $arg_r->{cgi_obj}
            : $self->perr('cgi_obj');
        my $lh
            = ( exists $arg_r->{lh_obj} )
            ? $arg_r->{lh_obj}
            : $self->perr('lh_obj');
        my $c_hr
            = ( exists $arg_r->{c_hr} )
            ? $arg_r->{c_hr}
            : $self->perr('c_hr');

        my $l = get_logger(__PACKAGE__);
        $l->debug("module [$MODULE]");
        $l->debug("rpc [$rpc]");
        $l->debug("cgi [$cgi]");

        my $c = ( $cgi->param('change') ) ? $cgi->param('change') : 0;
        if ( not defined $c ) { $c = 0; }
        $l->debug("change [$c]");

        my $d_ar = $self->get_index( { cmd => $cmd, rpc_obj => $rpc } );

        if ($c) {
            $d_ar = $self->do_switch(
                {
                    tpl_data_ar => $d_ar,
                    rpc_obj     => $rpc,
                    cgi         => $cgi,
                    change      => $c
                }
            );
        }

        my $module_hr = $self->get_module_name_register();

        foreach my $m ( sort keys %{$module_hr} ) {
            $l->debug("found registered module [$m]");
        }

        my $h_ar = [ $lh->maketext('Module Switch') ];
        my $path = "tpl/$c_hr->{cat_theme}/module_switch";
        $l->debug("template path [$path]");

        return {

            # cookies have to be returned (even if empty)
            cookie_hr => {},

            # point to the layout template, please use word layout.html
            layout => "$path/layout.html",

            # array ref for output, one anon hash ref for each part
            # this have 3 orderd parts: begin_html, tt2_hr, end_html
            # For valid anon hash keys ( like begin_html, tt2_hr, ...)
            # see CipUX::CAT::Web::Controller
            layout_ar => [
                { begin_html => 1, },
                { body_ar    => $h_ar },
                { body_ar    => [] },      # $page_ar
                {
                    tt2_hr => {
                        tpl      => "$path/index.html",
                        param_hr => {
                            SHOW_DEBUG => 0,
                            DATA       => $d_ar,
                            MODULE     => $MODULE,
                            PATH       => $path,
                            LOGIN      => $rpc->get_login(),
                            LOCALE     => $self->get_locale(),
                            THEME      => $self->get_theme(),
                            lh         => $lh,
                        },

                    },
                },
                {
                    footer_hr =>
                        { show_index_back => 1, show_script_back => 0 },
                },
                { end_html => 1, },
            ],
        };
    }

    # get all relevant object for the index
    sub get_index {

        my ( $self, $arg_r ) = @_;
        my $rpc
            = ( exists $arg_r->{rpc_obj} )
            ? $arg_r->{rpc_obj}
            : $self->perr('rpc_obj');
        my $cmd
            = exists $arg_r->{cmd}
            ? $self->l( $arg_r->{cmd} )
            : $self->perr('cmd');

        my $l = get_logger(__PACKAGE__);
        $l->debug("cmd [$cmd]");

        my $a_hr = $rpc->xmlrpc( { cmd => $cmd } );
        $l->debug( 'a_hr: ', { filter => \&Dumper, value => $a_hr } );

        if ( $a_hr->{status} eq 'FALSE' ) {
            $l->debug('answer is FALSE');

            $l->debug('build exception object');

            # TODO build EASY execption obj

        }
        $l->debug('answer is TRUE');

        # Filter all CAT, and use only CAT-Web  ( m{\.cgi$}smx
        my @tpl_data = ();
        my $r_hr     = $rpc->extract_data_for_tpl( { answer_hr => $a_hr } );
        my $d_ar     = $r_hr->{tpl_data_ar};
        foreach my $hr ( @{$d_ar} ) {
            $l->debug("CN [$hr->{cn}]");
            if ( $hr->{cn} =~ m{\.cgi$}smx ) {
                push @tpl_data, $hr;
            }
        }

        return \@tpl_data;
    }

    sub do_switch {

        my ( $self, $arg_r ) = @_;
        my $rpc
            = ( exists $arg_r->{rpc_obj} )
            ? $arg_r->{rpc_obj}
            : $self->perr('rpc_obj');
        my $d_ar
            = ( exists $arg_r->{tpl_data_ar} )
            ? $arg_r->{tpl_data_ar}
            : $self->perr('tpl_data_ar');
        my $cgi
            = ( exists $arg_r->{cgi} ) ? $arg_r->{cgi} : $self->perr('cgi');
        my $c
            = ( exists $arg_r->{change} )
            ? $arg_r->{change}
            : $self->perr('change');    # contains cn or 0

        my $l = get_logger(__PACKAGE__);

        foreach my $hr ( @{$d_ar} ) {
            next if not $c;
            next if $hr->{cn} ne $c;
            $l->debug("change object exists [$hr->{cn}] [$c]");
            if ( $hr->{cipuxIsEnabled} eq 'TRUE' ) {
                $l->debug("disable [$c]");

                # cipux_task_client -t cipux_task_disable_cat_module \
                #                   -o theme.cgi -x cipuxIsEnabled=FALSE
                my $cmd  = 'cipux_task_disable_cat_module';
                my $p_hr = { object => $c, cipuxIsEnabled => 'FALSE' };
                my $a_hr = $rpc->xmlrpc( { cmd => $cmd, param_hr => $p_hr } );
                $hr->{cipuxIsEnabled} = 'FALSE';
            }
            elsif ( $hr->{cipuxIsEnabled} eq 'FALSE' ) {
                $l->debug("enable [$c]");
                my $cmd  = 'cipux_task_enable_cat_module';
                my $p_hr = { object => $c, cipuxIsEnabled => 'TRUE' };
                my $a_hr = $rpc->xmlrpc( { cmd => $cmd, param_hr => $p_hr } );
                $hr->{cipuxIsEnabled} = 'TRUE';
            }
        }
        my $cmd = 'rpc_intern';
        $l->debug("cmd [$cmd]");
        my $p_hr = { subcmd => 'flush', };
        my $a_hr = $rpc->xmlrpc( { cmd => $cmd, param_hr => $p_hr } );

        return $d_ar;
    }
}

1;

