# -*- mode: perl; coding: utf-8 -*-
# $Id: 01index,v 1.1 2008-08-02 18:35:54 morimoto Exp $
# $Source: /home/ishikawa/work/keitairc/tmp/keitairc/t/02_Plugins/01index,v $

# WARNING: This file is a part of Keitairc::Plugins test suite, not
# actual working code.

$plugin = {
	name => 'index',
	action_imprementation => sub {
		my ($request, $name, $session_id, $param_string) = @_;

		::send_message($request);

		my $unread_channels = 0;
		my $accesskey = 1;

		my $format_mtime = sub{
			use encoding 'utf8';
			my $mtime = shift;
			return if($mtime <= 0);
			my $timediff = time - $mtime;
			if($timediff < 60){
				return $timediff . '秒';
			}
			if($timediff < 3600){
				return int($timediff/60) . '分';
			}
			if($timediff < 86400){
				return int($timediff/3600) . '時間';
			}
			if($timediff < 86400 * 30){
				return int($timediff/86400) . '日';
			}
			if($timediff < 86400 * 365){
				return int($timediff/86400/30) . 'ヶ月';
			}
			return int($timediff/86400/365) . '年';
			no encoding 'utf8';
		};

		my @loop;
		for my $cid ($::ib->channels()){
			my $p = {};
			my $channel = $::ib->cid2name($cid);
			my $cname = $::ib->simple_escape(encode($::cf->web_charset(), $::ib->compact_channel_name($cid)));
			if($accesskey < 10){
				$p->{link} =
					sprintf('<a accesskey="%1d" href="all/%d">[%1d] %s</a>',
						$accesskey,
						$cid,
						$accesskey,
						$cname);
			}else{
				$p->{link} =
					sprintf('<a href="all/%d">&nbsp;&nbsp;&nbsp; %s</a>',
						$cid, $cname);
			}
			$accesskey++;

			# 未読行数
			if($::ib->unread_lines($cid)){
				$p->{unread} =
					sprintf(' <a href="unread/%d">%s</a>',
						$cid,
						$::ib->unread_lines($cid));
				$unread_channels++;
			}

			$p->{mtime} = Encode::encode($::cf->web_charset(), $format_mtime->($::ib->mtime($cid)));
			push @loop, $p;
		}

		my $ci = new Keitairc::ClientInfo($request);
		my $view = new Keitairc::View($::cf, $ci);
		return $view->render('index.html',
				     {
					     loop => \@loop,
					     unread => $unread_channels,
				     });
	}
};

1;
