#!perl

use DBI;

my $dbh = DBI->connect('dbi:mysql:pokedex', 'perl', '');

my $sth = $dbh->prepare('SELECT id, base, chain FROM evchains');
my @pokemachus;
$sth->execute;
while (my $row = $sth->fetchrow_hashref) {
    recurse(undef, eval $row->{chain});
}

$sth = $dbh->prepare('UPDATE pokemon SET evparent=?, evmethod=?, evparam=? WHERE id=?');
for my $i (0 .. $#pokemachus) {
    printf "fixed %3d %3d: %s\n", $i, $pokemachus[$i]->{parent}, $pokemachus[$i]->{method} . ' + ' . $pokemachus[$i]->{param};
    $sth->execute(
        (defined $pokemachus[$i]->{parent} ? $pokemachus[$i]->{parent} + 1 : 0),
        $pokemachus[$i]->{method},
        $pokemachus[$i]->{param} || '',
        $i + 1,
    );
}





sub recurse {
    my ($parent, $obj) = @_;
    my @obj = @$obj;
    my $hash = $pokemachus[ $obj->[0] ] = { parent => $parent, object => $obj };

    my ($evcode, $evparam) = split //, $obj->[1], 2;

    if (!$evcode) { ; }
    elsif ($evcode eq 'F') { $hash->{method} = 'item'; $hash->{param} = 'Fire Stone' }
    elsif ($evcode eq 'M') { $hash->{method} = 'item'; $hash->{param} = 'Moon Stone' }
    elsif ($evcode eq 'W') { $hash->{method} = 'item'; $hash->{param} = 'Water Stone' }
    elsif ($evcode eq 'S') { $hash->{method} = 'item'; $hash->{param} = 'Sun Stone' }
    elsif ($evcode eq 'P') { $hash->{method} = 'item'; $hash->{param} = 'Leaf Stone' }
    elsif ($evcode eq 'T') { $hash->{method} = 'item'; $hash->{param} = 'Thunderstone' }
    elsif ($evcode eq 'L') { $hash->{method} = 'level'; $hash->{param} = $evparam }
    elsif ($evcode eq 'H') { $hash->{method} = 'happiness' }

    elsif ($evcode eq 'D') { $hash->{method} = 'unique-happydayoritem'; $hash->{param} = 'Sun Shard' }
    elsif ($evcode eq 'N') { $hash->{method} = 'unique-happynightoritem'; $hash->{param} = 'Moon Shard' }

    elsif ($evcode eq 'R') { $hash->{method} = 'trade' }
    elsif ($evcode eq 'I') { $hash->{method} = 'trade'; $hash->{param} = $evparam }

#    elsif ($evcode eq 'E') { return "Appears in open slot after a $PokeNames[$evparam] is evolved to" }
    elsif ($evcode eq 'E') { $hash->{method} = 'unique-divineintervention' }
    elsif ($evcode eq 'a') { $hash->{method} = 'unique-levelplusattack'; $hash->{param} = $evparam }
    elsif ($evcode eq 'd') { $hash->{method} = 'unique-levelplusdefense'; $hash->{param} = $evparam }
    elsif ($evcode eq 'e') { $hash->{method} = 'unique-levelplusequal'; $hash->{param} = $evparam }
    elsif ($evcode eq 'B') { $hash->{method} = 'unique-beauty' }
    else { die "wtf" }

    shift @obj; shift @obj;
    recurse($obj->[0], $_) for @obj;
}
