#!/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/service/imode/make/content/spec/screen_area/index.html';

do_task(@ARGV);

sub do_task {
    my $html = Jcode->new(get($URL))->tr('-', '0-9')->euc;
    $html =~ s/(?:\r?\n)+/\n/g;
    my $re = regexp();
    my %map;
    while ($html =~ /$re/igs) {
	my($model, $width, $height, $color, $depth) = ($1, $2, $3, $4, $5);
	$map{uc($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;
    $Data::Dumper::Terse  = 1;
    printf <<'TEMPLATE', Data::Dumper->Dump([ $map ]);
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);

BEGIN {
    if ($ENV{DOCOMO_MAP}) {
        eval q{
            require XML::Simple;
            my $xml = XML::Simple->new;
            $DisplayMap = $xml->XMLin($ENV{DOCOMO_MAP});
        };
        warn "using normal hash map: $@" if $@;
    }
}

$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">.*?(\d+)(\d+).*?</FONT></TD>
<TD><FONT SIZE="2">.*?</FONT></TD>
<TD><FONT SIZE="2">(|顼)(?:.*?)(\d+)(?:|Ĵ)</FONT></TD>
RE
    ;
}
