# -*- mode: perl; coding: utf-8 -*-
# keitairc/lib/plugins/32address
# based on 'Add link to google maps japan on address-like texts'
# by twk, from http://nonn-et-twk.net/twk/node/51
#

# The line number (1 incremented) and filename below must be
# actual. see perlsyn.
# line 12 "keitairc/lib/plugins/32address"

use Encode;
use utf8;

my $WHITESPACE_ex = q/[\s　:：()\[\]［］「」（）、。]/;
my $NO_WHITESPACE_ex = q/[^\s　:：()\[\]［］「」（）、。]/;
my $TODOFUKEN_ex = q/(?:東京都|北海道|(?:大阪|京都)府|(?:青森|岩手|宮城|秋田|山形|福島|茨城|栃木|群馬|埼玉|千葉|神奈川|新潟|富山|石川|福井|山梨|長野|岐阜|静岡|愛知|三重|滋賀|兵庫|奈良|和歌山|鳥取|島根|岡山|広島|山口|徳島|香川|愛媛|高知|福岡|佐賀|長崎|熊本|大分|宮崎|鹿児島|沖縄)県)(?![\d０-９])/;
my $CITY_SEPARATE_CHAR_ex = '(?:^|' . $WHITESPACE_ex . ')';
my $SHICHOSON_ex = $NO_WHITESPACE_ex . '{1,4}[郡市区]';
my $AZA_ex = $NO_WHITESPACE_ex . '{1,20}';
my $BANCHI_ex = q/[\d０-９]/ . '{1,8}'; # 一二三四五六七八九十東西南北無ABC
my $KYOTO_ex = q/京都[府市]\S{6,20}(?:(?:[上下][るル])|(?:[東西]入[るル]?)|入中)/;
my $BUILDING1_re = q/^[^\d０-９]+[\d０-９]+(?:(?:[-―－ー]|丁目|番地?|号)[\d０-９]+)+/;
my $BUILDING2_re = q/^(.*(?:丁目|番地?|号))[^地\d０-９]+(?:ビル|$)/;

my $re = {
	general =>
		'(?:' .
		  $TODOFUKEN_ex . '|' . $CITY_SEPARATE_CHAR_ex . $SHICHOSON_ex .
		')' . '[ \t　]*' .
		'(?:' .
		  $AZA_ex . '[ \t　]*' .
		  '(?:' . $BANCHI_ex . '(?:丁目|番地?|号)?[-―－ー]?)' . '{1,4}' .
		')' .
		'|' . $KYOTO_ex,
		building1 => $BUILDING1_re,
		building2 => $BUILDING2_re,
};

$plugin = {
	name => 'address',
	message_replace_regexp => '(' . $re->{general} . ')',

	message_replace_imprementation => sub {
		my ($request, $session_id, $src) = @_;
		my $ci = new Keitairc::ClientInfo($request);
		my $s = $src;
		$s =~ s/.*($re->{general}).*/$1/;
		# remove building names since google maps rarely recognize them
		$s =~ s/($re->{building1}).*/$1/;
		$s =~ s/$re->{building2}.*/$1/;
		if ($ci->is_webkit()) {
			# iPhone/iPod touch では google maps にリンクをはっとくと
			# google map アプリが起動してくれるので、それにまかせる
			return sprintf('<a target="_self" class="inline" href="http://maps.google.com/maps?q=%s">%s</a>',
				       URI::Escape::uri_escape_utf8($s), $src);
		} else {
			return sprintf('<a target="_self" class="inline" href="%s%s/address/%s">%s</a>',
				       $::cf->web_root(), $session_id,
				       URI::Escape::uri_escape_utf8($s), $src);
		}
	},

	action_imprementation => sub {
		my ($request, $name, $session_id, $param) = @_;
		my $ci = new Keitairc::ClientInfo($request);
		my $view = new Keitairc::View($::cf, $ci);
		my $address = Encode::deconde('utf8', URI::Escape::uri_unescape($param));
		return $view->render('address.html', {
			session_id => $session_id,
			address => $address,
			     });
	}
};

1;
