#!/usr/bin/perl

use warnings;
use strict;
use utf8;
use HTML::TreeBuilder;
use Data::Dumper;
use JSON;

binmode(STDOUT, ":utf8");

sub utext{
    my $f = shift;
    my %rmn = ("Ⅰ"=>"I", "Ⅱ"=>"II", "Ⅲ"=>"III", "Ⅳ"=> "IV", "Ⅴ"=>"V",
               "Ⅵ"=>"VI", "Ⅶ"=>"VII", "Ⅷ"=>"VIII", "Ⅸ"=>"IX",
               "Ⅹ"=>"X", "Ⅺ"=>"XI", "Ⅻ"=>"XII");
    $f =~ y/Ａ-Ｚａ-ｚ０-９：　（）/A-Za-z0-9: ()/;
    $f =~ s/^\s*//;
    $f =~ s/\s*$//;
    $f =~ s/\s+/ /g;
    for(keys(%rmn)){
        $f =~ s/$_/$rmn{$_}/;
    }
    return $f;
}
sub rn{
    return sprintf("%.3f", shift);
}

my $troot = HTML::TreeBuilder->new();
open(my $wtable_html_h, "<:utf8", $ARGV[0]) || die;
$troot->parse_file($wtable_html_h);
close($wtable_html_h);
my @tables = $troot->look_down(_tag=>"table");
my $clstable = pop(@tables);

my @clss = $clstable->look_down(_tag=>"tr");
shift(@clss)->push_content(["td", {width=>"300"}, "自分の状態"]);
my %clss;
for(@clss){
    my $clstr = $_;
    my @cls = $clstr->look_down(_tag=>"td");
    my $name = utext($cls[0]->as_text());
    my @list;
    my $maxunit = 0;
    for(split(/\s+/, utext($cls[1]->as_text()))){
        if(/^(.+?)\((.+)\):([0-9]+)$/){
            push(@list, [$1, $3], [$2, $3]);
            $maxunit += $3;
        }elsif(/^(.+):([0-9]+)$/){
            push(@list, [$1, $2]);
            $maxunit += $2;
        }
    }
    $clss{$name} = {units=>0, scoresum=>0, snumber=>0, maxunit=>$maxunit, subjects=>\@list, tr=>$clstr};
}

print(STDERR 'javascript:(function(){var%20l=document.getElementById("content").getElementsByTagName("form")[0].getElementsByTagName("table")[0].getElementsByTagName("tbody")[0].getElementsByClassName("column_odd"),i=0,n,t,k,a=[];for(;i<l.length;i++){t=l[i].getElementsByTagName("td");n=t[0].textContent.replace(/\\s/g,"");k=t[3].textContent.replace(/\\s/g,"");t=t[5].textContent.replace(/\\s/g,"");a.push([n,k,t])}open("","").document.body.textContent=eval(JSON.stringify(a))})()'."\n");

my %scores;
my $scoretable = decode_json(<STDIN>);
for(@$scoretable){
    if($_->[0] && $_->[1] && $_->[2]){
        $scores{utext($_->[0])} = utext($_->[2]);
    }
}

my %scoretable = (D=>0, C=>1, B=>2, A=>3, AA=>4);

for(keys(%clss)){
    my $sll = $clss{$_};
    for(@{$sll->{subjects}}){
        if($scores{$_->[0]} && defined($scoretable{$scores{$_->[0]}})){
            $sll->{units} += $_->[1] if($scoretable{$scores{$_->[0]}});
            $sll->{snumber}++;
            $sll->{scoresum} += $scoretable{$scores{$_->[0]}};
        }
    }
}

for(keys(%clss)){
    $clss{$_}{unitscore} = $clss{$_}{units}/$clss{$_}{maxunit};
    if($clss{$_}{snumber}){
        $clss{$_}{scorescore} = $clss{$_}{scoresum}/$clss{$_}{snumber}/4;
    }else{
        $clss{$_}{scorescore} = 0;
    }
}

my @kkss;
for(@tables){
    my @strs = $_->look_down(_tag=>"tr");
    my @gunt;
    my $topline = shift(@strs);
    for($topline->look_down(_tag=>"td")){
        push(@gunt, utext($_->as_text()));
    }
    $topline->push_content(["td", "点数"]);
    while(@strs){
        my @ud;
        my @ub;
        my @sd;
        my $kkstr = shift(@strs);
        for($kkstr->look_down(_tag=>"td")){
            push(@ud, utext($_->as_text()));
            push(@ub, $_->attr("rowspan")?$_->attr("rowspan")-1:0);
        }
        for(shift(@strs)->look_down(_tag=>"td")){
            push(@sd, utext($_->as_text()));
        }
        my $kksname = $ud[0];
        for(0 .. $#ub){
            if($ub[$_]){
                @sd = (@sd[0 .. ($_-1)], "", @sd[$_ .. $#sd]);
            }
        }
        my $score = 0;
        for(0 .. $#ub){
            my $gn = $gunt[$_];
            my $gob = $clss{$gn};
            my $scn = $ud[$_];
            my $scs = $sd[$_];
            if(!$gob){
                next;
            }
            if($scn !~ /^[0-9]+$/){
                $scn = 0;
            }
            if($scs !~ /^[0-9]+$/){
                $scs = 0;
            }
            if($ub[$_]){
                if($gn =~ /平均点$/){
                    $scs = $scn;
                    $scn = 0;
                }
            }
            $score += $scn/100 * $gob->{unitscore};
            $score += $scs/100 * $gob->{scorescore};
        }
        push(@kkss, {name=>$kksname, score=>$score, tr=>$kkstr});
    }
}

for(@kkss){
    $_->{tr}->push_content(["td", {rowspan=>2}, rn($_->{score} * 100)]);
}
for(keys(%clss)){
    $clss{$_}->{tr}->push_content(["td", 
        "獲得単位数:".$clss{$_}{units}."/".$clss{$_}{maxunit}
                                       ."=".rn($clss{$_}{unitscore}),
        ["br"],
        "合計点数,平均点数:".$clss{$_}{scoresum}.","
                            .rn($clss{$_}{scorescore}*4)
    ]);
}

print($troot->as_HTML);
