#!/usr/bin/perl -w
use strict;
use warnings;
use utf8;
use XML::Simple ();
use Encode;
use WWW::MobileCarrierJP::DoCoMo::Display;

do_task(@ARGV);

sub do_task {
    my $dat = WWW::MobileCarrierJP::DoCoMo::Display->scrape;
    my @maps;
    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が一致しない機種
        push @maps, +{
            model  => uc $phone->{model},
            width  => $phone->{width},
            height => $phone->{height},
            color  => $phone->{is_color},
            depth  => $phone->{depth},
        };
    }
    my $xml = XML::Simple->new;
    my $ref = $xml->XMLin( 't/DoCoMoMap.xml' );
    my %oldmap = ( map { $_->{ model } => 1 } @{ $ref->{ terminal } } );
    my %diff;
    for my $map ( @maps ) {
        my $model = $map->{ model };
        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";
    output_code( { terminal => \@maps } );
}

sub output_code {
    my ($map) = @_;
    my $xml = XML::Simple->new;
    printf <<'TEMPLATE', $xml->XMLout($map);
<?xml version="1.0" ?>
%s
TEMPLATE
}