#/*
# *  Copyright 2007-2009 hkrn <hikarin@users.sourceforge.jp>
# *
# *  Licensed under the Apache License, Version 2.0 (the "License");
# *  you may not use this file except in compliance with the License.
# *  You may obtain a copy of the License at
# *
# *      http://www.apache.org/licenses/LICENSE-2.0
# *
# *  Unless required by applicable law or agreed to in writing, software
# *  distributed under the License is distributed on an "AS IS" BASIS,
# *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# *  See the License for the specific language governing permissions and
# *  limitations under the License.
# */
#
# $Id: CS.pm 1826 2009-04-08 15:23:25Z hikarin $
#

package Img0ch::Template::CS;

use strict;
use ClearSilver qw();

sub new {
    my ( $iClass, $args ) = @_;
    my $bbs = $args->{bbs};
    my $uri = $args->{uri};

    my $iTemplate = bless {}, $iClass;
    $iTemplate->{__hdf}  = ClearSilver::HDF->new;
    $iTemplate->{__file} = $args->{filename};
    $iTemplate->param(
        {   BaseURI         => $uri,
            BBSPath         => $uri,
            BBSURI          => ( $bbs ? join( '/', $uri, $bbs ) : $uri ),
            BBS             => $bbs,
            CGIURI          => $args->{cgipath},
            StaticURI       => $args->{static},
            TimeStamp       => time(),
            VERSION         => $args->{version},
            Version         => Img0ch::Kernel->VERSION(),
            'hdf.loadpaths' => [ $args->{tmplpath} ],
            %{ $args->{setting} },
        }
    );
    $iTemplate;
}

sub param {
    my ( $iTemplate, $hash ) = @_;
    my $hdf = $iTemplate->{__hdf};
    while ( my ( $key, $val ) = each %$hash ) {
        _hdf_setValue( $hdf, $key, $val );
    }
}

sub render {
    my ($iTemplate) = @_;
    my $cs          = ClearSilver::CS->new( $iTemplate->{__hdf} );
    my $file        = $iTemplate->{__file};
    $cs->parseFile($file)
        or die 'ClearSilver RENDERING ERROR AT PARSING(OR RENDERING) ', $file,
        ': ', $!, "\n";
    \$cs->render();
}

sub remove_cache { }

my $switch = {
    'ARRAY' => sub {
        my ( $hdf, $key, $val ) = @_;
        my $index = 0;
        for my $value (@$val) {
            _hdf_setValue( $hdf, join( '.', $key, $index ), $value );
            $index++;
        }
    },
    'HASH' => sub {
        my ( $hdf, $key, $val ) = @_;
        while ( my ( $k, $v ) = each %$val ) {
            _hdf_setValue( $hdf, join( '.', $key, $k ), $v );
        }
    },
    'SCALAR' => sub {
        my ( $hdf, $key, $val ) = @_;
        _hdf_setValue( $hdf, $key, $$val );
    },
};

sub _hdf_setValue {
    my ( $hdf, $key, $val ) = @_;
    my $subref = $switch->{ ref $val || '' };
    $subref ? $subref->( $hdf, $key, $val ) : $hdf->setValue( $key, $val );
}

1;
__END__
