#/*
# *  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 164 2007-02-02 14:52:06Z hikarin $
#

package Zeromin::App::archive;

use strict;

sub load {
    require Zeromin::App::bbs;
    Zeromin::App::bbs::load(shift);
}

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

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

sub update {
    my ( $zApp, $method, $privilege, $success, $failed ) = @_;
    my $zUser = $zApp->user() || return { code => 1 };
    my $iBBS  = $zApp->bbs()  || return { code => 1 };

    $zUser->can_update_archive() or return { code => 1 };
    require Zeromin::Archive;
    my $zArchive = Zeromin::Archive->new($iBBS);
    $zArchive->load();
    $zArchive->update();
    $zApp->logger( 1, 'UPDATED ARCHIVE INDEX' );

    return { code => 0 };
}

sub _do_task {
    my ( $zApp, $method, $privilege, $success, $failed ) = @_;
    my $zUser = $zApp->user() || return { code => 1 };
    my $iBBS  = $zApp->bbs()  || return { code => 1 };
    my $iRequest = $zApp->request();
    my $status   = {};

    $zUser->$privilege or return { code => 1 };
    require Zeromin::Archive;
    my $zArchive = Zeromin::Archive->new($iBBS);
    my $dir      = $iBBS->get_name();
    my @keys     = $iRequest->param('key');
    $zArchive->load();

    for my $key (@keys) {
        $zArchive->set_key($key);
        if ( $zArchive->$method($key) ) {
            $zApp->logger( 1, "$success: %s/%s", [ $dir, $key ] );
            $status->{$key} = 1;
        }
        else {
            $zApp->logger( 0, "$failed: %s/%s", [ $dir, $key ] );
            $status->{$key} = 0;
        }
    }
    $zArchive->save();

    return { code => 0, done => $status };
}

1;
__END__
