#/*
# *  Copyright 2007-2010 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: Error.pm 2002 2010-02-21 13:28:07Z hikarin $
#

package Zeromin::Log::Error;

use strict;
use base qw( Img0ch::Error Zeromin::Log::Interface );

sub new {
    my ( $iClass, $iObject, $key, $ip_int ) = @_;
    my $class = ref $iObject || '';

    return $iClass->SUPER::new( $iObject, $key, $ip_int );
}

sub retrive_by_day {
    my ( $zLog, @args ) = @_;
    $zLog->SUPER::retrive_by_day( $zLog->{_kernel}, qr{/error\.\w+\z}xms,
        @args );
}

sub retrive_by_month {
    my ( $zLog, @args ) = @_;
    $zLog->SUPER::retrive_by_month( $zLog->{_kernel}, qr{/error\.\w+\z}xms,
        @args );
}

sub all {
    my ( $zLog, $re, $path ) = @_;
    $re   ||= qr{/error\.\w+\z};
    $path ||= File::Basename::dirname( $zLog->{_kernel}->get_repos_path(0) );
    $zLog->SUPER::all( $re, $path );
}

sub to_array {
    shift->SUPER::to_array( qr/\AI:L:E\.(?:.+?\.?:.+?\.\d+\.\d+)\.\w+\z/xms,
        @_ );
}

sub _retrive {
    my ( $zError, $repositories, $iKernel ) = @_;
    my $ret  = [];
    my $seen = {};

    for my $iRepos ( map { $iKernel->get_repos_nocache($_) } @$repositories )
    {
        $iRepos->iterate(
            sub {
                my ( $key, $value, $seen ) = @_;
                if ($key =~ m{
                    \AI:L:E\.(.*?)\.(.*?)\.(\d*?)\.(.*?)\.(\w+)\z
                    }xms
                    )
                {
                    my ( $bbs, $thread_key, $date, $mil, $name )
                        = ( $1, $2, $3, $4, $5 );
                    my $prefix = "I:L:E.${bbs}.${thread_key}.${date}.${mil}";
                    exists $seen->{$prefix} and return 0;
                    $seen->{$prefix} = $date;
                }
                return 0;
            },
            $seen,
        );
        while ( my ( $prefix, $date ) = each %$seen ) {
            my ( undef, $bbs, $thread_key, $date, undef ) = split /\./,
                $prefix;
            my $error = $iRepos->get("${prefix}.error") or next;
            my $ip    = $iRepos->get("${prefix}.ip")    or next;
            push @$ret,
                {
                bbs   => $bbs,
                key   => $thread_key,
                ip    => $ip,
                date  => $date,
                error => $error,
                };
        }
    }
    @$ret = sort { $b->{date} cmp $a->{date} } @$ret;
    return $ret;
}

1;
__END__
