# -*-perl-*-
# Keitairc::View
# $Id: View.pm,v 1.2 2008/01/09 18:49:17 morimoto Exp $
# $Source: /cvsroot/keitairc/lib/Keitairc/View.pm,v $
#
# Copyright (c) 2008 Jun Morimoto <morimoto@mrmt.net>
# This program is covered by the GNU General Public License 2

package Keitairc::View;
use strict;
use HTML::Template;
use HTTP::Response;
use Keitairc::Config;
use Keitairc::ClientInfo;

################################################################
sub new{
	my $proto = shift;
	my $cf = shift;
	my $ci = shift;
	my $session_id = shift;
	my $me = {};
	$me->{Config} = $cf;
	$me->{ClientInfo} = $ci;
	if(defined $session_id){
		$me->{session_id} = $session_id;
	}
        bless $me;
}

################################################################
sub redirect{
	my $me = shift;
	my $path = shift;

	$path = sprintf('http://%s:%d%s%s',
			$me->{Config}->web_host(),
			$me->{Config}->web_port(),
			$path);
	::log_debug("path [$path]");
	my $response = HTTP::Response->new(302);
	$response->push_header('Location', $path);
	$response;
}

################################################################
sub template_path{
	my $me = shift;
	my $template = shift;
	for my $template_dir (split(':', $me->{Config}->template_dir())){
		if(-r "$template_dir/$template"){
			return "$template_dir/$template";
		}
	}
}

################################################################
sub render{
	my $me = shift;
	my $template = shift;
	my $vars = shift;
	my $t = new HTML::Template(
		filename => $me->template_path($template),
		die_on_bad_params => 0,
		cache => 1);
	$t->param(title => $me->{Config}->web_title());
	$t->param(version => $me->{Config}->version());
	$t->param(viewport => $me->{ClientInfo}->is_ipod());
	$t->param(timestamp => timestamp());
	if(defined $vars){
		$t->param($vars);
	}
	my $response = HTTP::Response->new(200);
	$response->push_header('Content-type', 'text/html; charset=Shift_JIS');
	$response->content($t->output());
	$response;
}

################################################################
sub timestamp{
	my ($sec, $min, $hour, $day, $mon, $year) = localtime(time);
	sprintf('%d/%d/%d %02d:%02d:%02d',
		$year+1900, $mon+1, $day, $hour, $min, $sec);
}

1;
