# +========================================================================+
# || Copyright (C) 2006 - 2009 Christian Kuelker                          ||
# ||                                                                      ||
# || License: GNU General Public License - GNU GPL - version 2            ||
# ||          or (at your opinion) any later version                      ||
# +========================================================================+
#  ID:       $Id: Index.pm 4900 2010-07-03 13:27:21Z christian-guest $
#  Revision: $Revision: 4900 $
#  Head URL: $HeadURL: svn+ssh://christian-guest@svn.debian.org/svn/cipux/trunk/cipux-core/cat-web/lib/CipUX/CAT/Web/Module/Index.pm $
#  Date:     $Date: 2010-07-03 15:27:21 +0200 (Sat, 03 Jul 2010) $
#  Source:   $Source$

package CipUX::CAT::Web::Module::Index;

use 5.008001;
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
    # name of the module or module array
    Readonly::Scalar my $NAME   => 'index';
    Readonly::Scalar my $MODULE => 'index.cgi';

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

    # OBJECT
    my %register_module_of : ATTR( :set<register_module>);

    # METHOD
    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 base will be called first
    sub module_cfg : CUMULATIVE(BASE FIRST) {

        my $self = shift;

        my $add       = 'The index show all registered CAT-Web modules.';
        my $module_hr = {};
        $module_hr->{cipuxName}             = $NAME;
        $module_hr->{cipuxEntity}           = 'cat_module';
        $module_hr->{cipuxModality}         = 'cat';
        $module_hr->{cipuxIcon}             = $NAME . '.png';
        $module_hr->{cipuxDescription}      = $add;
        $module_hr->{cipuxShortDescription} = 'module overview';
        $module_hr->{cipuxTask}             = \@TASK;

        # not used, but to be correct:
        $module_hr->{cipuxScript}        = $NAME . '.cgi';
        $module_hr->{cipuxTemplate}      = 'index.html';
        $module_hr->{cipuxTemplateDir}   = 'index';
        $module_hr->{cipuxIsModuleArray} = 'FALSE';

        return [$module_hr];
    }

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

        my ( $self, $arg_r ) = @_;
        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 $view
            = ( exists $arg_r->{view_obj} )
            ? $arg_r->{view_obj}
            : $self->perr('view_obj');
        my $lh
            = ( exists $arg_r->{lh_obj} )
            ? $arg_r->{lh_obj}
            : $self->perr('lh_obj');
        my $mod_access_hr
            = ( exists $arg_r->{mod_access_hr} )
            ? $arg_r->{mod_access_hr}
            : {};
        my $c_hr = ( exists $arg_r->{c_hr} ) ? $arg_r->{c_hr} : {};

        my $l = get_logger(__PACKAGE__);
        $l->debug("module [$MODULE]");
        $l->debug("theme [$c_hr->{cat_theme}]");
        $l->debug("rpc [$rpc]");
        $l->debug("cgi [$cgi]");
        $l->debug( 'mod_access_hr: ',
            { filter => \&Dumper, value => $mod_access_hr } );

        #  Index
        #  BasicObject
        #    aux: room, netgroup
        #    user: admin, assistant, lecturer, professor, pupil, student,
        #          teacher, tutor
        #    group: class, course, group, lecture, reading, seminar,
        #           studygroup, team, tutorial, workshop
        #  CipUX::CAT::Web::Module::Assignment
        #    group: class, course, group, lecture, reading, seminar,
        #           studygroup, team, tutorial, workshop
        #    other: skel
        #    aux:   role_assignment
        #  CipUX::CAT::Web::Module::CatModule
        #
        #  internetadmin
        #  examadmin
        #  transferadmin
        #  import
        #  client

        my $cmd = $TASK[0];
        my $a_hr = $rpc->xmlrpc( { cmd => $cmd } );

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

            my $msg = 'RPC call failed, got no list of CAT modules!';
            if (    exists $a_hr->{msg}
                and defined $a_hr->{msg}
                and $a_hr->{msg} )
            {
                $msg .= q{ } . $a_hr->{msg};
            }
            return $self->exception( { 'module' => $MODULE, msg => $msg } );

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

        # Filter all CAT, and use only CAT-Web  ( m{\.cgi$}smx
        my @tpl_data = ();

        #my ($d_ar, $sorted_ar)
        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} ) {
            my $m = $hr->{cn};
            $l->debug("module (CN) [$m]");
            next if $m eq 'index.cgi';
            next if $hr->{cipuxIsEnabled} ne 'TRUE';
            next if not exists $mod_access_hr->{$m};
            next if not defined $mod_access_hr->{$m};
            next if not $mod_access_hr->{$m};

            #$hr->{NAME} = $lh->maketext($hr->{cipuxName});
            $hr->{NAME} = $hr->{cipuxName};

            #my $dummy =  $lh->maketext('admin');
            #$hr->{NAME} =~ s{_}{ }smxg;
            #$hr->{NAME} = $self->get( $hr->{NAME} );

            if ( $hr->{cn} =~ m{\.cgi$}smx ) {
                push @tpl_data, $hr;
            }
        }

        my $login = $rpc->get_login();

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

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

        my $header_ar = [$lh->maketext('Module Index')];
        my $path      = "tpl/$c_hr->{cat_theme}/$NAME";
        $l->debug("template path [$path]");
        $l->debug("template login [$login]");

        $l->debug( '@tpl_data', { filter => \&Dumper, value => \@tpl_data } );

        return {

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

            # point to the layout template, please use the word
            # "layout.html" if possible
            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    => $header_ar },
                { body_ar    => [] },           # $page_ar
                { statusline => 1 },
                {
                    tt2_hr => {
                        tpl      => "$path/index.html",
                        param_hr => {
                            SHOW_DEBUG => 0,
                            DATA       => \@tpl_data,
                            MODULE     => $MODULE,
                            PATH       => $path,
                            MAXCOL     => $self->get_max_col(),
                            lh         => $lh,
                        },

                    }
                },
                {
                    formbuilder_hr =>
                        { form => scalar $view->logout( { lh_obj => $lh } ) },
                },
                { footer_hr => {}, },
                { end_html  => 1, },
            ],
        };
    }

}
1;

__END__
