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

package Zeromin2::App::archive;

use strict;
use Zeromin::Archive qw();

sub create {
    _task(
        shift, 'can_create_archive',
        'CREATED ARCHIVE',
        'TRIED CREATING ARCHIVE', 'create'
    );
}

sub remove {
    _task(
        shift, 'can_remove_archive',
        'REMOVED ARCHIVE',
        'TRIED REMOVING ARCHIVE', 'remove'
    );
}

sub update {
    my ($zApp) = @_;
    $zApp->check_csrf() or return $zApp->return_value(1);
    $zApp->privilege( 'can_update_archive', 1 )
        or return $zApp->return_value(1);

    my $zBBS     = $zApp->bbs();
    my $bbs      = $zBBS->get_name();
    my $zArchive = Zeromin::Archive->new($zBBS);
    $zArchive->load();
    $zArchive->update();
    $zApp->logger( 1, 'UPDATED ARCHIVE INDEX: %s', [$bbs] );

    return $zApp->return_value(0);
}

sub _task {
    my ( $zApp, $priv_meth, $success, $fail, $method ) = @_;
    $zApp->check_csrf() or return $zApp->return_value(1);
    $zApp->privilege( $priv_meth, 1 ) or return $zApp->return_value(1);

    my @param = $zApp->request()->param('thread');
    scalar @param or return $zApp->return_value(2);

    my $zBBS     = $zApp->bbs();
    my $bbs      = $zBBS->get_name();
    my $status   = {};
    my $zArchive = Zeromin::Archive->new($zBBS);

    $zArchive->load();
    for my $key (@param) {
        $zArchive->set_key($key);
        if ( $zArchive->$method ) {
            $zApp->logger( 1, ( $success . ': %s/%s' ), [ $bbs, $key ] );
            $status->{$key} = 1;
        }
        else {
            $zApp->logger( 0, ( $fail . ': %s/%s' ), [ $bbs, $key ] );
            $status->{$key} = 0;
        }
    }

    $zArchive->save();
    return $zApp->return_value( 0, $status );
}

1;
__END__
