# -*- cperl -*-
# -----------------------------------------------------------------------------
# $Id: LogPurger.pm,v 1.3 2004/12/11 05:41:54 admin Exp $
# -----------------------------------------------------------------------------
package Celaenito::LogPurger;
use strict;
use warnings;
use POE::Session;
use Celaenito::DB;
use Celaenito::Logger;
use Celaenito::Config;
use Hash::Util qw(lock_keys);
use constant ALIAS => 'logpurger';
use constant INTERVAL => 30 * 60;

sub run {
    my $class = shift;
    my $this = bless {} => $class;

    lock_keys %$this;

    POE::Session->create(
	heap => $this,
	inline_states => {
	    _start   => \&_start_handler,
	    _stop    => \&_stop_handler,
	    shutdown => \&_shutdown_handler,
	    purge    => \&_purge_handler,
	},
       );
}

sub _start_handler {
    $_[KERNEL]->alias_set(ALIAS);
    $_[KERNEL]->delay('purge', INTERVAL);

    logdebug sprintf
      'will purge old logs every %.2f minutes.', INTERVAL / 60;
}

sub _stop_handler {
    logdebug 'STOPPED.';
}

sub _shutdown_handler {
    $_[KERNEL]->alias_remove(ALIAS);
    $_[KERNEL]->delay('purge');
}

sub _purge_handler {
    #logdebug 'woke up.';
    # FIXME: PoCo::EasyDBIを使ひ、非同期で行ふやうに。
    
    my $lim = config('log.limit');

    # 24時間經過してゐないjob_queueログは消してはならない。
    # as possibleモードの爲。
    my @tables = (
	[job_queue =>
	   'WHERE status = "done" AND '.
	     'UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(begin_time) > 24 * 60 * 60' =>
	       'begin_time'],
	[job_log   =>
	   '' =>
	     'exec_time' ],
       );
    foreach my $table (@tables) {
	my ($count) = DB->selectrow_array(
	    qq{SELECT COUNT(*) FROM $table->[0] $table->[1]});
	my $rows_to_del = $count - $lim;
	if ($rows_to_del > 0) {
	    my $sql = qq{
DELETE FROM $table->[0]
$table->[1]
 ORDER BY $table->[2] ASC
 LIMIT $rows_to_del
};
	
	    my $rows = DB->do($sql);
	    $rows += 0;

	    lognotice sprintf
	      'deleted %d rows from %s', $rows, $table->[0];
	}
	else {
	    #logdebug sprintf
	    #  '%s does not have so many old logs.', $table->[0];
	}
    }

    #logdebug 'is going to sleep again...';
    $_[KERNEL]->delay('purge', INTERVAL);
}

1;
