#/*
# *  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: NGWord.pm 457 2007-04-04 14:32:56Z hikarin $
#

package Img0ch::Filter::NGWord;

use strict;

sub new {
    my ( $iClass, $iBBS ) = @_;
    my $iKernel = $iBBS->get_kernel();

    bless {
        _bbs => ( $iBBS->get_name() || 'test' ),
        _rs => $iKernel->get_repos( $iKernel->get_repos_path('ngword') ),
    }, $iClass;
}

sub load { $_[0]->{_rs}->load(); return 1 }

sub write_ok {
    my ( $iFNGW, $input ) = @_;
    my $iRepos       = $iFNGW->{_rs};
    my $bbs          = $iFNGW->{_bbs};
    my $prefix_top   = 'I:F:N';
    my $prefix_regex = qr/\AI:F:N\.$bbs\.(.+?)\./xms;
    my $id_table     = {};

    $iRepos->iterate(
        sub {
            my ( $key, $value, $bbs, $id_table, $prefix_regex ) = @_;
            if ($key =~ /$prefix_regex/) {
                $id_table->{"${bbs}.$1"} = 1;
            }
            elsif ($key =~ /\AI:F:N\.test\.(.+?)\./xms) {
                $id_table->{"test.$1"} = 1;
            }
            return 0;
        },
        $bbs,
        $id_table,
        $prefix_regex
    );

    for my $id ( keys %{$id_table} ) {
        my $prefix = "${prefix_top}.${id}";
        my $flag   = $iRepos->get_int("${prefix}.flag") || next;
        my $regex  = $iRepos->get_binary("${prefix}.regex");
        while ( my ( $key, $text ) = each %$input ) {
            $text or next;
            if ( $text =~ /$regex/xms ) {
                if ( $flag & 4 ) {
                    my $to = $iRepos->get_binary("${prefix}.replace");
                    $text =~ s/$regex/$to/gxms;
                    $input->{$key} = $text;
                    next;
                }
                elsif ( $flag & 2 ) {
                    $text =~ s/$regex//gxms;
                    $input->{$key} = $text;
                    next;
                }
                else {
                    return 0;
                }
            }
        }
    }
    1;
}

1;
__END__
