# -*- mode: perl; coding: utf-8 -*-
# keitairc/lib/plugins/00unread
# チャネルの未読メッセージ閲覧

# The line number (1 incremented) and filename below must be
# actual. see perlsyn.
# line 10 "keitairc/lib/plugins/00unread"

$plugin = {
	name => 'unread',
	action_imprementation => sub {
		my ($request, $name, $session_id, $param_string) = @_;
		my $cid = $param_string;
		my $channel = $::ib->cid2name($cid);

		::send_message($request, $channel);

		my @loop;
		if(defined($::ib->cid2name($cid))){
			my ($tp, $np, $mp, $rp) = $::ib->buffer_ptr($cid);
			if(defined $tp){
				my @range = (0 .. @{$tp}-1);
				@range = reverse @range if $::cf->reverse_unread();
				my ($last_date, $current_date) = ('', undef);
				for my $lp (@range){
					next if @{$rp}[$lp];
					my $p = {};
					$current_date = $::ib->format_date(@{$tp}[$lp]);
					unless($last_date eq $current_date){
						$last_date = $current_date;
						my $pp = {};
						$pp->{date} = $current_date;
						push @loop, $pp;
					}

					$p->{time} = $::ib->format_time(@{$tp}[$lp]);
					$p->{nick} = $::ib->simple_escape(@{$np}[$lp]);
					my $message = $::ib->colorize($::ib->simple_escape(@{$mp}[$lp])) || '';
					for my $name ($::pl->list_replace_plugins()){
						last if $message =~ s/$::pl->{plugins}->{$name}->{message_replace_regexp}/$::pl->{plugins}->{$name}->{message_replace_imprementation}($request, $session_id, $1, $2, $3, $4, $5, $6, $7, $8, $9)/eg;
					}
					$message =~ s/\s+$//;
					$message =~ s/\s+/ /g;
					$p->{message} = $message;
					@{$rp}[$lp] = 1;
					push @loop, $p;
				}
			}
		}

		my $ci = new Keitairc::ClientInfo($request);
		my $view = new Keitairc::View($::cf, $ci);
		my $cname = $::ib->simple_escape($::ib->compact_channel_name($cid));
		return $view->render('unread.html', {
			loop => \@loop,
			channel_compact => $cname,
			follow_nick => $::cf->follow_nick(),
			cid => $cid,
			     });
	}
};

1;
