#/*
# *  Copyright 2007 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: banner.pm 363 2007-03-16 15:11:10Z hikarin $
#

package Zeromin::App::banner;

use strict;
use Unicode::Japanese qw();

sub load {
    my ($zApp) = @_;
    my $zUser = $zApp->user() || return { code => 1 };
    Unicode::Japanese->new( _load($zApp), $zApp->kernel()->get_encoding(1), )
        ->get();
}

sub preview {
    my ($zApp)  = @_;
    my $iKernel = $zApp->kernel();
    my $iConfig = $iKernel->get_config();
    my $static = join '/', $iConfig->get('SystemPath'), 'init';
    my $id     = $zApp->request()->param_int('id');
    my $html   = q{
<html><head><title>BANNER PREVIEW</title>
<meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<meta http-equiv="Content-Style-Type" content="text/css">
</head>};
    if ( $id != 3 ) {
        $html .= qq{
<body style="background-image: url(${static}/default_bac.gif)">
}
    }
    $zApp->encoding( $iKernel->get_encoding() );
    $html =~ s/\A\n//xms;
    $html =~ s/\n+/\n/gxms;
    $html .= _load($zApp) . "\n";
    $html .= '</body></html>';
    $html;
}

sub save {
    my ($zApp) = @_;
    my $zUser = $zApp->user() || return { code => 1 };
    $zUser->can_edit_banner() or return { code => 1 };

    require Zeromin::Metadata;
    my $iKernel  = $zApp->kernel();
    my $zMeta    = Zeromin::Metadata->new($iKernel);
    my $iRequest = $zApp->request();
    my $encoding = $iKernel->get_encoding(1);
    my $id       = $iRequest->param_int('id');
    my $link     = [
        undef,
        sub { $zMeta->main_banner(@_) },
        sub { $zMeta->sub_banner(@_) },
        sub { $zMeta->mobile_banner(@_) },
    ];
    ( $id < 1 or $id > 3 ) and $id = 1;
    $link->[$id]->( \$iRequest->param_multibyte( 'content', $encoding, 1 ) );
    $zApp->logger(
        1,
        'MODIFIED BANNER: %s',
        [ [ undef, 'main', 'sub', 'mobile' ]->[$id] ]
    );
    { code => 0 };
}

sub _load {
    require Zeromin::Metadata;
    my ($zApp) = @_;
    my $zMeta  = Zeromin::Metadata->new( $zApp->kernel() );
    my $id     = $zApp->request()->param_int('id');
    my $link   = [
        undef,
        sub { $zMeta->main_banner() },
        sub { $zMeta->sub_banner() },
        sub { $zMeta->mobile_banner() },
    ];
    ( $id < 1 or $id > 3 ) and $id = 1;
    $link->[$id]->();
}

1;
__END__
