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

package Img0ch::Maple::DD;

use strict;
use DBM::Deep qw();

sub new {
    my ( $iClass, $iKernel, $path ) = @_;
    bless {
        __dd       => undef,
        __filename => $path,
        __kernel   => $iKernel,
    }, $iClass;
}

sub load {
    my ( $iRepos, $path ) = @_;
    $path ||= $iRepos->{__filename};
    $iRepos->{__dd} = DBM::Deep->new($path)
        or $iRepos->{__kernel}->throw_io_exception($path);
    return 1;
}

sub save {1}

sub set {
    my ( $iRepos, $key, $value ) = @_;
    my $dd = $iRepos->{__dd};
    $dd->put( $key, $value )
        or $iRepos->{__kernel}->throw_exception( $dd->error() );
    return;
}

*set_binary = \&set;

sub get {
    my ( $iRepos, $key ) = @_;
    my $dd = $iRepos->{__dd};
    $dd->exists($key) or return '';
    return $dd->get($key);
}

*get_binary = \&get;

sub decode_binary { shift; return $_[0] }

sub is_binary_safe {1}

sub get_int { Img0ch::Kernel::intval( $_[0]->get( $_[1] ) ) }

sub remove {
    my ( $iRepos, $key ) = @_;
    my $dd = $iRepos->{__dd};
    $dd->exists($key) or return '';
    my $oldvalue = $dd->get($key);
    $dd->delete($key) or $iRepos->{__kernel}->throw_exception( $dd->error() );
    return $oldvalue;
}

sub iterate {
    my ( $iRepos, $code_ref, @args ) = @_;
    my $iKernel = $iRepos->{__kernel};
    my $dd      = $iRepos->{__dd};

    my $key = $dd->first_key();
    while ($key) {
        my $value = $dd->get($key);
        my $status = $code_ref->( $key, \$value, @args );
        if ( $status > 0 ) {
            $dd->put( $key, $value )
                or $iKernel->throw_exception( $dd->error() );
        }
        elsif ( $status < 0 ) {
            $dd->delete($key) or $iKernel->throw_exception( $dd->error() );
        }
        $key = $dd->next_key($key);
    }

    return 1;
}

*iterate_binary = \&iterate;

1;
__END__
