# -*- mode: perl; coding: utf-8 -*-
# Keitairc::Log::File
#
# Copyright (c) 2010 ISHIKAWA Mutsumi <ishikawa@hanzubon.jp>
# This program is covered by the GNU General Public License 2

package Keitairc::Log::File;

use Keitairc::Config;
use POSIX qw(strftime);
use FileHandle;
use File::Path;
use strict;
use warnings;

sub new {
	my ($proto, $arg) = @_;
	my $cf = $arg->{config};

	my $me = {};
	$me->{debug} = $cf->debug();

	my ($type, $dir) = split(':', $cf->log(), 2);
	$me->{dir} = $dir || $ENV{HOME} . '/.keitairc.d/log';

	mkpath($me->{dir}) if (!-e $me->{dir});
	if (!-w $me->{dir}) {
		print STDERR 'keitairc [ERROR]: Log dir ' . $me->{dir} . " not writable\n";
		return 0;
	}

	$me->{fh} = {};
	bless $me;
	$me->_log_open();
	$me;
}

sub log_access {
	my ($me, $m) = @_;
	$me->_log('access', $m);
}

sub log_info {
	my ($me, $m) = @_;
	$me->_log('info', $m);
}

sub log_error {
	my ($me, $m) = @_;
	$me->_log('error', $m);
}

sub log_debug {
	my ($me, $m) = @_;
	$me->_log('debug', $m) if ($me->{debug});
}

sub log_close {
	my ($me) = @_;
	close($me->{fh}->{access}) if (defined $me->{fh}->{access});
	close($me->{fh}->{info}) if (defined $me->{fh}->{info});
	close($me->{fh}->{error}) if (defined $me->{fh}->{error});
	close($me->{fh}->{debug}) if ($me->{debug} && defined $me->{fh}->{debug});
}

sub _current {
	strftime("%Y%m%d", localtime);
}

sub _log_open {
	my ($me) = @_;
	my $current = $me->_current();

	if (!defined $me->{prev} || $me->{prev} != $current) {
		$me->{prev} = $current;

		close($me->{fh}->{access}) if (defined $me->{fh}->{access});
		close($me->{fh}->{info}) if (defined $me->{fh}->{info});
		close($me->{fh}->{error}) if (defined $me->{fh}->{error});

		$me->{fh}->{access} = *STDOUT if (!open($me->{fh}->{access}, '>> ' . $me->{dir} . '/access_' . $current . '.log'));
		$me->{fh}->{access}->autoflush(1);

		$me->{fh}->{info} = *STDOUT if (!open($me->{fh}->{info}, '>> ' . $me->{dir} . '/info_' . $current . '.log'));
		$me->{fh}->{info}->autoflush(1);

		$me->{fh}->{error} = *STDERR if (!open($me->{fh}->{error}, '>> ' . $me->{dir} . '/error_' . $current . '.log'));
		$me->{fh}->{error}->autoflush(1);

		if ($me->{debug}) {
			close($me->{fh}->{debug}) if (defined $me->{fh}->{debug});
			$me->{fh}->{debug} = *STDERR if (!open($me->{fh}->{debug}, '>> ' . $me->{dir} . '/debug_' . $current . '.log'));
			$me->{fh}->{debug}->autoflush(1);
		}
	}
}

sub _log {
	my ($me, $out, $m) = @_;
	$me->_log_open();
	my $fh = $me->{fh}->{$out};
	print $fh $m . "\n";
}

1;
