#! /usr/bin/perl
use strict;
use warnings;

# Parses songlist from the DDRNO wiki

print "begin;\n";

while (<>) {
	m/
	  \|   \s* \[\[ (.*?) \]\] \s*    # song name
          \|\| \s* \[\[ (.*?) \]\] \s*    # artist
	  \|\| \s*      (\d+(?:-(\d+))?)  \s*    # bpm
	  \|\| \s*      (\d+)      \s*    # single beginner
	  \|\| \s*      (\d+)      \s*    # single standard
	  \|\| \s*      (\d+)      \s*    # single difficult 
	  \|\| \s*      (\d+)      \s*    # single expert
	  \|\| \s*
	  \|\| \s*      (\d+)      \s*    # double standard
	  \|\| \s*      (\d+)      \s*    # double difficult
	  \|\| \s*      (\d+)      \s*    # double expert
	 /x or next;
	 
	my ($songname, $artist, $minbpm, $maxbpm, $sb, $ss, $sd, $se, $ds, $dd, $de) = 
	   ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11);

	# fix some wikisyntax ickyness :-)
	$artist =~ s/\]\]//g;
	$artist =~ s/\[\[//g;

	# minimal SQL escaping
	$songname =~ s/'/\\'/g;
	$artist =~ s/'/\\'/g;

	$maxbpm = $minbpm if (!defined($maxbpm));
	($maxbpm,$minbpm) = ($minbpm,$maxbpm) if ($maxbpm < $minbpm);

	printf "INSERT INTO songs (title,artist,minbpm,maxbpm) VALUES ('%s','%s',%u,%u);\n",
		$songname, $artist, $minbpm, $maxbpm;
	
	for my $t (['single', 'beginner', $sb],
                   ['single', 'standard', $ss],
                   ['single', 'difficult', $sd],
                   ['single', 'expert', $se],
                   ['double', 'standard', $ds],
                   ['double', 'difficult', $dd],
                   ['double', 'expert', $de]) {
		printf "INSERT INTO songratings (song,playmode,difficulty,feetrating) VALUES ((SELECT song FROM songs WHERE title='%s'),'%s','%s',%u);\n",
			$songname, $t->[0], $t->[1], $t->[2];
	}
}

printf "commit;\n";
