# +========================================================================+
# || Copyright (C) 2009 by 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::View;

use 5.008001;
use warnings;
use strict;
use Class::Std;
use CGI::Carp qw(carpout fatalsToBrowser warningsToBrowser cluck);
use CGI::FormBuilder;
use Data::Dumper;
use Date::Manip;
use English qw( -no_match_vars);
use Log::Log4perl qw(get_logger :levels);
use Readonly;
use Sys::Hostname;

use base qw(CipUX CipUX::CAT::Web::L10N);
{

    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{};

    # OBJECT
    my %login_of :
        ATTR( init_arg => 'cat_login' :set<login> :default('view_login') );
    my %session_of :
        ATTR( init_arg => 'cat_session' :set<session> :default('view_session') );
    my %locale_of :
        ATTR( init_arg => 'cat_locale' :set<locale> :default('en') );
    my %theme_of :
        ATTR( init_arg => 'cat_theme' :set<theme> :default('default') );

    sub login {
        my ( $self, $arg_r ) = @_;

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

        my $l    = get_logger(__PACKAGE__);
        my $path = $self->get_path;
        $l->debug("path [$path]");

        my $demo              = 0;
        my $demo_restore_time = 'unknown';
        if (    exists $cfg_hr->{base}->{catweb_demo}
            and defined $cfg_hr->{base}->{catweb_demo}
            and $cfg_hr->{base}->{catweb_demo} eq "1" )
        {
            $demo = 1;
            my $fn = '/usr/share/cipux-cat-web/tpl/TIME_STAMP';
            open my $f, q{<}, $fn or croak "Can not open $fn!";
            my @TS = <$f>;
            close $f;

            #2010-01-07T12:17:45
            $TS[0] =~ m{^(\d+-\d+-\d+T\d+:\d+:\d+)$}mx;
            if ($1) {
                $demo_restore_time = $1;
            }
        }

        my $style    = $path . '/form.css';
        my $template = $path . '/login/index.html';
        my $form     = CGI::FormBuilder->new(
            method => 'post',
            fields => [qw/cat_theme cat_locale cat_login cat_password/],
            submit => [ $lh->maketext('OK') ],

            #params => $cat{cgi},
            keepextra  => 1,
            debug      => 0,
            reset      => 0,
            sticky     => 0,
            stylesheet => $style,
            template   => {
                type     => 'TT2',
                template => $template,
                variable => 'form',
                data     => {
                    lh                => $lh,
                    DEMO              => $demo,
                    DEMO_RESTORE_TIME => $demo_restore_time,
                },
            }
        );

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

        #my $locale_hr = { de-de => 'German', en => 'English' };
        my $locale_hr
            = $self->i18n_locale( { lh_obj => $lh, cfg_hr => $cfg_hr } );
        my $theme_hr
            = $self->i18n_theme( { lh_obj => $lh, cfg_hr => $cfg_hr } );

        $form->field( name => 'cat_password', type => 'password' );

        # TODO : get that from cfg
        $form->field(
            name  => 'server_name',
            type  => 'text',
            value => 'TEST'
        );
        $form->field(
            name       => 'cat_locale',
            type       => 'select',
            selectname => 0,
            size       => 1,
            value      => $locale_of{ ident $self},
            options    => $locale_hr
        );
        $form->field(
            name       => 'cat_theme',
            type       => 'select',
            selectname => 0,
            size       => 1,
            value      => $theme_of{ ident $self},
            options    => $theme_hr
        );

        my $param_hr = {
            theme  => $theme_of{ ident $self},
            locale => $locale_of{ ident $self}
        };
        my $r_hr = {
            cookie_hr => {
                cat_login   => $login_of{ ident $self},
                cat_session => $session_of{ ident $self},
                cat_locale  => $locale_of{ ident $self},
                cat_theme   => $theme_of{ ident $self},
            },
            layout    => "$path/login/layout.html",
            layout_ar => [
                { begin_html     => 1, },
                { formbuilder_hr => { form => $form }, },
                { footer_hr      => {}, },
                { end_html       => 1, },
            ],

        };

        #return ( SCALAR {$form} HASHREF {$r_hr} );
        return ($r_hr);

    }

    sub logout {
        my ( $self, $arg_r ) = @_;
        my $lh
            = ( exists $arg_r->{lh_obj} )
            ? $arg_r->{lh_obj}
            : $self->perr('lh_obj');

        my $path = $self->get_path;
        my $form = CGI::FormBuilder->new(
            method     => 'post',
            fields     => [qw(cat_login cat_session )],
            submit     => [ $lh->maketext('logout') ],
            action     => 'cat.cgi',
            params     => undef,
            debug      => 0,
            sticky     => 0,
            keepextra  => 1,
            table      => 0,
            reset      => 0,
            sticky     => 0,
            stylesheet => $path . '/form.css',
            template   => {
                type     => 'TT2',
                template => $path . '/logout/logout.html',
                variable => 'form',
                }

        );
        $form->field(
            name  => 'cat_login',
            type  => 'hidden',
            value => 'login',
            force => 1
        );
        $form->field(
            name  => 'cat_session',
            type  => 'hidden',
            value => 'login',
            force => 1
        );
        my $r_hr = {
            cookie_hr => { cat_login => 'login', cat_session => 'login', },
            layout    => "$path/logout/layout.html",
            layout_ar => [
                { begin_html     => 1, },
                { formbuilder_hr => { form => $form }, },
                { end_html       => 1, },
            ],

        };

        #return ( SCALAR {$form} HASHREF {$r_hr} );
        return $form;

    }

    sub footer {
        my ( $self, $arg_r ) = @_;

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

        my $show_index_back
            = (     exists $arg_r->{show_index_back}
                and defined $arg_r->{show_index_back}
                and $arg_r->{show_index_back} > 0 ) ? 1 : 0;

        my $show_script_back
            = (     exists $arg_r->{show_script_back}
                and defined $arg_r->{show_script_back}
                and $arg_r->{show_script_back} > 0 ) ? 1 : 0;

        my $script_back
            = (     exists $arg_r->{script_back}
                and defined $arg_r->{script_back}
                and $arg_r->{script_back} ne $EMPTY_STRING )
            ? $arg_r->{script_back}
            : 'cat.cgi';

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

        my $path = $self->get_path;
        $l->debug("path [$path]");

        return {
            layout    => "$path/footer/layout.html",
            layout_ar => [
                {
                    tt2_hr => {
                        tpl      => "$path/footer/index.html",
                        param_hr => {
                            SHOW_DEBUG       => 0,
                            SHOW_INDEX_BACK  => $show_index_back,
                            SHOW_SCRIPT_BACK => $show_script_back,
                            SCRIPT_BACK      => $script_back,
                            DATA             => [ 'hallo', 'hello' ],
                            MODULE           => 'footer',
                            VERSION          => $VERSION,
                            PATH             => $path,
                        },

                    },
                },
            ],
        };

    }

    sub status_line {
        my ( $self, $arg_r ) = @_;

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

        my $logger = get_logger(__PACKAGE__);
        $logger->debug('START');
        $logger->debug("self [$self]");

        my $path = $self->get_path;

        return {
            cookie_hr => {
                cat_login   => $login_of{ ident $self},
                cat_session => $session_of{ ident $self},
                cat_locale  => $locale_of{ ident $self},
                cat_theme   => $theme_of{ ident $self},
            },
            layout    => "$path/status_line/layout.html",
            layout_ar => [
                {
                    tt2_hr => {
                        tpl      => "$path/status_line/index.html",
                        param_hr => {
                            SHOW_DEBUG  => 0,
                            DATA        => [ 'hallo', 'hello' ],
                            MODULE      => 'statusline',
                            SERVER      => hostname,
                            ROLE        => 'TODOrole',
                            STATUS      => 'TODOstatus',
                            INSTITUTION => 'TODOinstitution',
                            CUSTOMER    => 'TODOcustom',
                            DATE        => $self->get_date,
                            VERSION     => $VERSION,
                            PATH        => $path,
                            LOGIN       => $login_of{ ident $self},
                            LOCALE      => $locale_of{ ident $self},
                            THEME       => $theme_of{ ident $self},
                            SESSION     => $session_of{ ident $self},
                        },

                    },
                },
            ],
        };

    }

    sub get_path {

        my ( $self, $arg_r ) = @_;

        my $path = "tpl/$theme_of{ident $self}";

        return $path;
    }

    sub get_date {

        return UnixDate( 'today', '%Y-%m-%dT%H:%M' );

    }

}
1;

__END__


