#!/usr/bin/perl

# Generate questions for the Moodle system. Accepts question numbers
# as command line arguments, and generates random values for the
# question text.

# USAGE:
#   $0 2 3 4 5 6

use strict;
use warnings;

use utf8;
use Unicode::UCD 'charinfo';

binmode(STDIN,  "utf8");
binmode(STDOUT, "utf8");
binmode(STDERR, "utf8");

@ARGV = (0) unless @ARGV;

for my $NR (@ARGV) {

    # A set of Unicode ranges with different number of characters:
    my @r = ([0,0x7F],[0x80,0x7FF],[0x800,0xFFFF],[0x10000,0x10FFFF]);

    # $ri is a Range Index:
    my $ri = int(rand(@r));

    # Generate a random character code:
    my $c = $r[$ri][0] + int(rand($r[$ri][1] - $r[$ri][0]));

    # Get the randomly generated character:
    my $ch = chr($c);

    my $ci = charinfo($c);

    my $NAME = $ci->{name};
    $NAME = "" unless defined $NAME;

    my $CHPRINT = $ch;
    if ($NAME eq "" || $NAME =~ /^<.*>$/) {
        $CHPRINT = "";
    }
    
    my $DEC = sprintf ("%d", $c);
    my $HEX = sprintf ("%06X", $c);
    my $BIN = sprintf ("%021b", $c);

    my $NBYTES = $ri + 1;
                                                                                                                                                                                        
my $template = <<EOF;
<?xml version="1.0" encoding="UTF-8"?>
<quiz>
  <question type="numerical">
    <name>
      <text>03 how many UTF-8 bytes does a unicode character need ($NR)</text>
    </name>
    <questiontext format="html">
      <text><![CDATA[<p dir="ltr" style="text-align: left;">How many bytes does the following Unicode character (more precisely, a code point) need when encoded in UTF-8?</p><p dir="ltr" style="text-align: left;">Kiek baitų reikės, norint užkoduoti žemiau pateiktą Unikodo simbolį (tiksliau, kodo tašką) UTF-8 koduotėje?</p><p dir="ltr" style="text-align: left;"><strong>${NAME}<br>${DEC} DEC, ${HEX} HEX, ${BIN} BIN, $CHPRINT </strong><br></p>]]></text>
    </questiontext>
    <generalfeedback format="html">
      <text></text>
    </generalfeedback>
    <defaultgrade>1.0000000</defaultgrade>
    <penalty>0.3333333</penalty>
    <hidden>0</hidden>
    <idnumber></idnumber>
    <answer fraction="100" format="moodle_auto_format">
      <text>$NBYTES</text>
      <feedback format="html">
        <text></text>
      </feedback>
      <tolerance>0</tolerance>
    </answer>
    <unitgradingtype>0</unitgradingtype>
    <unitpenalty>0.1000000</unitpenalty>
    <showunits>3</showunits>
    <unitsleft>0</unitsleft>
  </question>

</quiz>
EOF

    print $template;
}
