#!/usr/bin/perl -w
use strict;
use FindBin;
use Jcode;
use LWP::Simple;
use Data::Dumper;
use HTTP::MobileAgent;

my $URL = 'http://www.nttdocomo.co.jp/p_s/imode/spec/ryouiki.html';

do_task(@ARGV);

sub do_task {
    my $html = Jcode->new(get($URL))->tr('-', '0-9')->euc;
    $html =~ s/\n+/\n/g;
    my $re = regexp();
    my %map;
    while ($html =~ /$re/gs) {
	my($model, $width, $height, $color, $depth) = ($1, $2, $3, $4, $5);
	$map{$model} = {
	    width => $width,
	    height => $height,
	    color => $color eq '顼',
	    depth => $depth,
	};
    }
    my $overwrite = $ARGV[0] && $ARGV[0] eq '-o';
    output_code(\%map, $overwrite);
}

sub output_code {
    my($map, $overwrite) = @_;
    if ($overwrite) {
	open MAP, "> $FindBin::Bin/../lib/HTTP/MobileAgent/DoCoMoDisplayMap.pm" or die $!;
	select MAP;
    }
    $Data::Dumper::Indent = 1;
    printf <<'TEMPLATE', Data::Dumper->Dump([ $map ], [ qw(DisplayMap) ]);
package HTTP::MobileAgent::DoCoMoDisplayMap;
# This file is autogenerated by makedocomomap
# in HTTP-MobileAgent distribution

use strict;
require Exporter;
use base qw(Exporter);

use vars qw(@EXPORT_OK $DisplayMap);
@EXPORT_OK = qw($DisplayMap);

%s

1;
TEMPLATE
    ;
    if ($overwrite) {
	close MAP;
    }
}

sub regexp {
    return <<'RE';
<TD><FONT SIZE="2">([A-Z]+\d+\w*)</FONT></TD>
<TD><FONT SIZE="2">.*?</FONT></TD>
<TD><FONT SIZE="2">.*?</FONT></TD>
<TD><FONT SIZE="2">(.*?)(.*?)</FONT></TD>
<TD><FONT SIZE="2">.*?</FONT></TD>
<TD><FONT SIZE="2">(|顼)(\d+)(?:|Ĵ)</FONT></TD>
RE
    ;
}
