#/*
# *  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: VTA.pm 850 2007-06-23 11:39:18Z hikarin $
#

package Img0ch::App::VTA;

use strict;

sub new {
    my ( $iClass, $iKernel, @args ) = @_;
    bless {
        __bbs     => undef,
        __config  => $iKernel->get_config(),
        __error   => '',
        __kernel  => $iKernel,
        __key     => 0,
        __option  => '',
        __request => Img0ch::Request->new(@args),
        __setting => undef,
        __thread  => undef,
    }, $iClass;
}

sub run {
    my ($iApp) = @_;
    $iApp->init() or return $iApp->redirect_error('init');

    my $iRequest = $iApp->{__request};
    my $user     = $iRequest->param('user');
    my $pass     = $iRequest->param('pass');
    my ( $result, $iTemplate, $ctype, $body );
    if ( $user and $pass ) {
        ( $result, $iTemplate, $ctype, $body )
            = $iApp->process( $user, $pass );
    }
    else {
        ( $result, $iTemplate, $ctype, $body ) = $iApp->render();
    }

    $result or return $iApp->redirect_error('remove');
    my $iRequest = $iApp->{__request};
    $iRequest->send_http_header( $ctype || 'text/html' );
    $iTemplate ? $iTemplate->flush() : $iRequest->print($body);
    return 1;
}

sub init {
    my ($iApp) = @_;
    my $iRequest = $iApp->{__request};
    $iRequest->init( $iApp->{__config} );

    my $bbs    = $iRequest->bbs();
    my $key    = $iRequest->param_int('key');
    my $resno  = $iRequest->param_int('resno');
    my $option = $iRequest->param('option');
    if ( my $path_info = $iRequest->path_info() ) {
        my @path = split '/', $path_info;
        ( $path[1] || 'test' ) =~ /([\w\-]+)/xms;
        $bbs = $1;
        ( $path[2] || '00000000' ) =~ /(\d{9,10})/xms;
        $key = $1;
        ( $path[3] || '0' ) =~ /(\d+)/xms;
        $resno = $1;
        $option ||= $path[4] || '';
    }

    require Img0ch::BBS;
    my $iBBS = Img0ch::BBS->new( $iApp->{__kernel}, { bbs => $bbs, } );
    if ( !$iBBS->get_id() ) {
        $iApp->{__error} = 'INVALID_POST';
        return 0;
    }
    $iApp->{__bbs} = $iBBS;

    require Img0ch::Setting;
    my $iSetting = Img0ch::Setting->new($iBBS);
    $iSetting->load();
    $iApp->{__setting} = $iSetting;

    require Img0ch::Thread;
    my $iThread = Img0ch::Thread->new( $iBBS, $key );
    if ( !$iThread->load() ) {
        $iApp->{__error} = 'INVALID_POST';
        return 0;
    }
    $iApp->{__key}    = $key;
    $iApp->{__option} = $option;
    $iApp->{__thread} = $iThread;

    return 1;
}

sub process {
    my ( $iApp, $user, $pass ) = @_;
    my $iBBS           = $iApp->{__bbs};
    my $iRequest       = $iApp->{__request};
    my $key            = $iApp->{__key};
    my $template_param = {};

    require Img0ch::Thread::Virtual;
    my $iTVirtual = Img0ch::Thread::Virtual->new( $iBBS, $key );
    if ( $iTVirtual->is_valid( $user, $pass ) ) {
        %$template_param = (
            Validate => 1,
            User     => $user,
            Pass     => $pass,
        );
        my $page = $iRequest->param('mode');
        my $priv = $iTVirtual->get_privilege($user);
        $priv & $iTVirtual->administrator()
            and $priv = $iTVirtual->all_privileges();
        if ( $page eq 'setting' ) {
            my @setting_keys = $iRequest->param('setting');
            if (    @setting_keys
                and $priv & $iTVirtual->can_change_setting() )
            {
                for my $setting_key (@setting_keys) {
                    my $value = $iRequest->param($setting_key);
                    $iTVirtual->set_setting( $setting_key, $value );
                }
                $iTVirtual->save();
                $template_param->{DoneSaveSetting} = 1;
            }
            my @keys = qw(
                BBS_COLUMN_NUMBER BBS_DATMAX BBS_LINE_NUMBER BBS_MAIL_COUNT
                BBS_MESSAGE_COUNT BBS_NAME_COUNT BBS_RES_MAX
            );
            %$template_param = (
                %$template_param,
                ( map { ( $_ => $iTVirtual->get_setting($_) ) } @keys ),
                ModeSetting => 1,
            );
        }
        else {
            my $thread = sub {
                my ( $method, $arguments, $template_name, $iBBS, $key ) = @_;
                require Zeromin::Thread;
                my $zThread = Zeromin::Thread->new( $iBBS, $key );
                $zThread->load();
                $zThread->$method(@$arguments);
                $zThread->save();
                $template_param->{"Done${template_name}"} = 1;
                return;
            };
            my $access = sub {
                my ( $method, $arguments, $template_name, $iBBS, $key ) = @_;
                require Img0ch::Log;
                my $iLog  = Img0ch::Log->new( $iBBS, $key );
                my $stack = [];
                my $call  = $method . '_denial_remote_host';
                for my $i (@$arguments) {
                    $i = Img0ch::Kernel::intval($i) || next;
                    my $ip = $iLog->get($i)->[1] || next;
                    my $host = gethostbyaddr( $ip, 2 ) || unpack( 'C*', $ip );
                    $host and $iTVirtual->$call($host);
                }
                $iTVirtual->save();
                $template_param->{"Done${template_name}RemoteHost"} = 1;
                return;
            };
            if ( my $method = $iRequest->param('method') ) {
                if (    $method eq 'remove_res'
                    and $priv & $iTVirtual->can_remove_res() )
                {
                    my @resno = $iRequest->param('resno');
                    $thread->(
                        'remove', [ \@resno ],
                        'RemoveRes', $iBBS, $key
                    );
                }
                elsif ( $method eq 'remove_file'
                    and $priv & $iTVirtual->can_remove_file() )
                {
                    my @resno = $iRequest->param('resno');
                    $thread->(
                        'remove', [ \@resno, { is_file_only => 1 } ],
                        'RemoveFile', $iBBS, $key
                    );
                }
                elsif ( $method eq 'stop'
                    and $priv & $iTVirtual->can_stop_thread() )
                {
                    $thread->( 'stop', [], 'StopThread', $iBBS, $key );
                }
                elsif ( $method eq 'restart'
                    and $priv & $iTVirtual->can_restart_thread() )
                {
                    $thread->( 'restart', [], 'RestartThread', $iBBS, $key );
                }
                elsif ( $method eq 'deny'
                    and $priv & $iTVirtual->can_control_access() )
                {
                    my @resno = $iRequest->param('resno');
                    $access->( 'set', \@resno, 'Deny', $iBBS, $key );
                }
                elsif ( $method eq 'allow'
                    and $priv & $iTVirtual->can_control_access() )
                {
                    my @resno = $iRequest->param('resno');
                    $access->( 'remove', \@resno, 'Allow', $iBBS, $key );
                }
            }
            $template_param->{View} = 1;
        }
    }
    else {
        $template_param->{AuthFailed} = 1;
    }

    return $iApp->render($template_param);
}

sub render {
    my ( $iApp, $template_param ) = @_;
    my $iBBS      = $iApp->{__bbs};
    my $iRequest  = $iApp->{__request};
    my $key_param = $iApp->{__key};
    my $validate  = $template_param->{Validate};

    require Img0ch::Subject;
    my $iSubject      = Img0ch::Subject->new($iBBS);
    my $i             = 1;
    my $subject_stack = [];
    $iSubject->load();
    for my $key ( @{ $iSubject->to_array() } ) {
        my $subj = $iSubject->get($key);
        push @{$subject_stack},
            {
            res      => $subj->[1],
            key      => $key,
            subject  => $subj->[0],
            count    => $i,
            index    => $i,
            selected => ( $key eq $key_param ),
            };
        $i++;
    }

    if ($validate) {
        require Img0ch::App::Mock::Read;
        my $reader = Img0ch::App::Mock::Read->new( $iBBS, $key_param,
            $iApp->{__option} );
        %$template_param = ( %$template_param, %{ $reader->run() } );
    }

    require Img0ch::Metadata;
    require Img0ch::Template;
    my $iMeta     = Img0ch::Metadata->new($iBBS);
    my $iTemplate = Img0ch::Template->new(
        $iBBS,
        {   file    => 'vta',
            request => $iRequest,
            setting => $iApp->{__setting},
        }
    );
    $iTemplate->param(
        {   %$template_param,
            Banner  => $iMeta->main_banner(),
            KEY     => $key_param,
            META    => $iMeta->meta(),
            Option  => $iApp->{__option},
            Threads => $subject_stack,
        }
    );

    return ( 1, $iTemplate, 'text/html', undef, );
}

sub redirect_error {
    my ( $iApp, $reason ) = @_;
    my $iKernel  = $iApp->{__kernel};
    my $iRequest = $iApp->{__request};
    my $key      = $iRequest->key();
    my $ip       = $iRequest->ip_int();

    require Img0ch::Error;
    my $iError = Img0ch::Error->new( $iKernel, $key, $ip );
    my $long = $iError->get( $iApp->{__error} || 'INVALID_POST' );
    $iError->record();

    if ( $iRequest->param('js') ) {
        $iRequest->send_http_header( 'text/javascript', 'UTF-8' );
        $iRequest->print(
            $iRequest->get_json( { ok => 0, error => $reason } ) );
    }
    else {
        require Img0ch::Template;
        my $iTemplate = Img0ch::Template->new(
            ( $iApp->{__bbs} || $iKernel ),
            {   file    => ('error'),
                request => $iRequest,
                setting => $iApp->{__setting},
            }
        );
        $iTemplate->param(
            {   Banner       => '',
                Flag         => 0,
                LongErrorStr => $long,
            }
        );
        my $iConfig = $iApp->{__config};
        my $charset = $iConfig->get('DefaultCharset');
        $iRequest->send_http_header( 'text/html', $charset );
        $iTemplate->flush();
    }
}

1;
__END__
