#!/usr/bin/perl -w
use strict;
use utf8;
use FindBin;
use lib "$FindBin::Bin/../lib";
use Data::Dumper;
use HTTP::MobileAgent;
use Encode;
use File::Spec;
use WWW::MobileCarrierJP::DoCoMo::Display;
use UNIVERSAL::require;

do_task(@ARGV);

sub do_task {
    my $dat = WWW::MobileCarrierJP::DoCoMo::Display->scrape;
    my %map;
    for my $phone (@$dat) {
        $phone->{model} =~ s/-//; # サイト上では N-04A と表記されているが、UA にふくまれているのは N04A なので。
        $phone->{model} =~ s/^(?:P0[789]|N0[6789]|F0[89]|SH0[567])A$/$&3/; # 型番とUAが一致しない機種
        $map{ uc $phone->{model} } = +{
            width  => $phone->{width},
            height => $phone->{height},
            color  => $phone->{is_color},
            depth  => $phone->{depth},
        };
    }
    my %diff;
    {
        HTTP::MobileAgent::DoCoMoDisplayMap->require or die $!;
        my %oldmap = %{ $HTTP::MobileAgent::DoCoMoDisplayMap::DisplayMap };
        for my $model ( keys %map ) {
            if ( $oldmap{ $model } ) {
                $diff{ exists }->{ $model } = delete $oldmap{ $model };
            }
            elsif ( !$oldmap{ $model } ) {
                $diff{ add }->{ $model } = delete $oldmap{ $model };
            }
        }
        for my $model ( keys %oldmap ) {
            $diff{ remove }->{ $model } = delete $oldmap{ $model };
        }
        warn "--- Added ---\n";
        warn join( ",", sort keys %{ $diff{ add } } ), "\n";
        warn "--- Removed ---\n";
        warn join( ",", sort keys %{ $diff{ remove } } ), "\n";
    }
    my $overwrite = $ARGV[0] && $ARGV[0] eq '-o';
    output_code( \%map, $overwrite );
}

sub output_code {
    my ( $map, $overwrite ) = @_;
    my $fh;
    if ($overwrite) {
        open $fh, '>', File::Spec->catfile($FindBin::Bin, qw/ .. lib HTTP MobileAgent DoCoMoDisplayMap.pm/)
          or die $!;
        select $fh;
    }
    $Data::Dumper::Indent = 1;
    $Data::Dumper::Terse  = 1;
    $Data::Dumper::Sortkeys = 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;
            my $map = $xml->XMLin($ENV{DOCOMO_MAP});
            if ($map->{terminal}) {
                # new layout
                for my $terminal (@{$map->{terminal}}) {
                    my $model = delete $terminal->{model};
                    $DisplayMap->{$model} = $terminal;
                }
            }
            else {
                # old layout
                $DisplayMap = $map;
            }
        };
        warn "using normal hash map: $@" if $@;
    }
}

$DisplayMap ||= %s;

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