#/*
# *  Copyright 2007-2008 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: Mobile.pm 1661 2008-03-09 23:53:39Z hikarin $
#

package Img0ch::App::Mobile;

use strict;
use base qw(Img0ch::App::Read);

sub run {
    my ($iApp) = @_;
    if ($iApp->init(
            {   disable => 'DisableMobileInitPlugin',
                type    => 'mobile.init',
                mobile  => 1,
            }
        )
        )
    {
        my $filter = sub {
            ${ $_[0] } =~ tr/\n//d;
            ${ $_[0] } =~ tr/\r\t/\n\n/;
            ${ $_[0] };
        };
        if ( $iApp->{_param_key} ne '0000000000' ) {
            $iApp->load_thread(
                {},
                {   filter   => $filter,
                    mobile   => 1,
                    template => 'i_read',
                    type     => 'mobile.rewrite',
                }
            );
        }
        else {
            $iApp->load_subject($filter);
        }
    }
    else {
        $iApp->redirect_error();
    }
}

sub load_thread {
    my ( $iApp, $template_vars, $option, $no_disk ) = @_;
    my $iConfig       = $iApp->{_config};
    my $iRequest      = $iApp->{_request};
    my $server        = $iConfig->get('Server');
    my $cgi           = $iRequest->get_app_uri();
    my $raw           = $iApp->{_param_raw};
    my $renderer      = $iConfig->get('MobileRenderer') || 'r.cgi';
    my $setting_saved = $iApp->get_param('mode') eq 'SET';
    my $query         = $iRequest->query()
        || $iApp->{_query_with_extend_params};
    my ( $aas_path, $aas_dir ) = $server =~ m{http://(.+?)/(.*)?}xms;

    $query = Img0ch::Kernel::escape_html_entities($query);
    $query =~ s/&amp;/&/gxms;
    $query =~ s/&?mode=SET&?//xms;
    $iRequest->escape_uri( \$query );

    if ( ( $aas_dir || '' ) ne '' ) {
        $aas_dir =~ s{/\z}{}xms;
        $aas_dir =~ tr|/|+|;
        $aas_path .= '+' . $aas_dir;
    }

    my $is_aas = $iApp->get_param('1a')
        || ( rindex( $raw, 'a' ) >= 0 ? 1 : 0 );
    my $is_copy    = rindex( $raw, 'c' ) >= 0   ? 1 : 0;
    my $is_setting = rindex( $raw, 'SET' ) >= 0 ? 1 : 0;
    my $is_write   = rindex( $raw, 'w' ) >= 0   ? 1 : 0;
    my $is_form   = $is_write || $is_setting || $setting_saved;
    my $omit_name = $iApp->get_param('1b');
    my $thumbnail = $iApp->get_param('t');
    $option->{br2nl}     = $is_copy;
    $option->{noname}    = $omit_name;
    $option->{thumbnail} = $thumbnail;

    my $iKernel = $iApp->{_kernel};
    my $name    = $iApp->get_param('FROM');
    $name and $name = $iKernel->get_encoded_str($name);

    my $mail = $iApp->get_param('mail');
    $mail and $mail = $iKernel->get_encoded_str($mail);

    my ( $raw_noa, $raw_noc ) = ( $raw, $raw );
    $raw_noa =~ s/a//gxms;
    $raw_noc =~ s/c//gxms;

    %{$template_vars} = (
        AAS             => $is_aas,
        AASBase         => $aas_path,
        ALinkColor      => $iApp->get_param('alink'),
        BackGroundColor => $iApp->get_param('bgc'),
        BaseQueryString => ( $setting_saved ? '' : $query ),
        CR              => "\r",
        Copy            => $is_copy,
        Fontsize        => $iApp->get_param_int('size'),
        KEY             => $iApp->{_param_key},
        LinkColor       => $iApp->get_param('link'),
        NameByCookie    => $name,
        MailByCookie    => $mail,
        MailPostAddress => $iConfig->get('MailPostAddress'),
        OmitDefaultName => $omit_name,
        QueryString     => $query,
        RCGIURI         => join( '/', $cgi, $renderer ),
        RawOption       => $raw,
        RawOptionNoA    => $raw_noa,
        RawOptionNoC    => $raw_noc,
        SettingForm => ( $is_setting and !$setting_saved ),
        SettingSaved => $setting_saved,
        TextColor    => $iApp->get_param('txt'),
        Thumbnail    => $thumbnail,
        VLinkColor   => $iApp->get_param('vlink'),
        Write        => $is_form,
        WriteForm    => $is_write,
    );
    $iApp->SUPER::load_thread( $template_vars, $option, $no_disk );
}

sub load_subject {
    my ( $iApp, $filter, $no_disk ) = @_;
    my $iBBS     = $iApp->{_bbs};
    my $iRequest = $iApp->{_request};
    my $iSetting = $iApp->{_setting};

    my $iMeta    = $iBBS->get_metadata_instance();
    my $iSubject = $iBBS->get_subject_instance();
    $iSubject->load();

    my $word  = $iRequest->param('s');
    my $found = [];
    if ($word) {
        my $result = $iSubject->search($word);
        map { push @$found, [ $_, @{ $result->{$_} } ] } keys %$result;
    }
    else {
        map { push @$found, [ $_, @{ $iSubject->get($_) } ] }
            @{ $iSubject->to_array() };
    }

    my $raw = $iApp->{_param_raw};
    my $floatable 
        = $iApp->get_param_int('THREAD')
        || $iSetting->get_int('BBS_MB_THREAD_NUMBER')
        || 1;

    my $copy = ( $raw =~ /[cC]\z/xms ) ? 1 : 0;
    my $start              = Img0ch::Kernel::intval($raw) || 1;
    my $read_subject_stack = [];
    my $i                  = 1;

    for my $subject (@$found) {
        if ( $i >= $start and $i < $start + $floatable ) {
            push @{$read_subject_stack},
                {
                res     => $subject->[2],
                key     => $subject->[0],
                subject => $subject->[1],
                index   => $i,
                };
        }
        $i++;
    }
    my $count = @{$read_subject_stack};
    my $prev = ( $count ? $start : $iSubject->count() ) - $floatable;

    my $iTemplate = $iBBS->get_template_instance(
        {   file    => 'i_threads',
            request => $iRequest,
            setting => $iSetting,
        }
    );
    my $iConfig = $iApp->{_config};

    my $query = $iRequest->query() || $iApp->{_query_with_extend_params};
    $iRequest->escape_uri( \$query );

    my $server              = $iRequest->get_app_uri();
    my $renderer            = $iConfig->get('MobileRenderer') || 'r.cgi';
    my $template_parameters = {
        ALinkColor      => $iApp->get_param('alink'),
        BackGroundColor => $iApp->get_param('bgc'),
        Banner          => $iMeta->mobile_banner(),
        CR              => "\r",
        Copy            => $copy,
        Count           => $count,
        Current         => $start,
        Fontsize        => $iApp->get_param_int('size'),
        From            => $start + 100,
        LinkColor       => $iApp->get_param('link'),
        MailByCookie    => $iApp->get_param('mail'),
        NameByCookie    => $iApp->get_param('FROM'),
        Next            => $start + $floatable,
        Prev            => ( ( !$count or $prev > 0 ) ? $prev : 0 ),
        QueryString     => $query,
        RCGIURI    => join( '/', $server, $renderer ),
        RawOption  => $raw,
        Search     => $word,
        TextColor  => $iApp->get_param('txt'),
        Threads    => $read_subject_stack,
        VLinkColor => $iApp->get_param('vlink'),
        Write => ( rindex( $raw, 'w' ) >= 0 ? 1 : 0 ),
    };

    if ($no_disk) {
        return $template_parameters;
    }
    else {
        $iTemplate->param($template_parameters);
        $iRequest->send_http_header('text/html');
        $iTemplate->flush($filter);
        return 1;
    }
}

1;
__END__
