#!/usr/bin/perl

use strict;
use utf8::all;

my @pen;
my @ppl;
my @palavras;
my $enTopic;
my $plTopic;

my %funcoes = lertemplates();
my $replacer = "---xx---";
my $input_str_rep = $funcoes{"inputLine"};

my @strings_arr;

while (<>) {
    if (/(.*?)\s=\s(.*?)\s*=\s*(.*)/) {        
        $enTopic = $2;
        $plTopic = $3;
    } else {
        push (@strings_arr, $_);
    }
}
shuffle_array(\@strings_arr);
my $string = join("", @strings_arr);

while ($string =~ /(.*?)\s*=\s*(.*)/g) {
    push(@pen, $1);
    my $orig = $2;
    my $changed = $2 =~ s/\[.*?\]/$replacer/gr;
    $changed = criarLinha($changed, $input_str_rep, $replacer);
    push(@ppl, $changed);
    while ($orig =~ /\[(.*?)\]/g) {
        push(@palavras, $1);
    }
}

my $linhas;
for (0..(@pen-1)) {
    $linhas .= ".".($_+1).aplicafuncao(
        "linha",
        en => $pen[$_],
        pl => $ppl[$_]) 
}
# print $linhas;
my @shuf_palavras = map {lc($_)} @palavras;
shuffle_array(\@shuf_palavras);
my $result = aplicafuncao(
    "mkexer",
    enTopic => $enTopic,
    plTopic => $plTopic,
    appl => join (",", map {qq("$_")} @palavras),
    appl2 => join (", ", map {qq($_)} @shuf_palavras),
    linhas => $linhas
);

print $result;

# ---------------------
sub aplicafuncao {
    my $nome = shift;
    my %params = @_;
    my $result = $funcoes{$nome};
    for (keys %params) {
       $result =~ s/§$_\b/$params{$_}/g;
    }
    return $result;
}

sub shuffle_array {
    my $array = shift;
    my $i = @$array;
    while ( --$i ) {
        my $j = int rand( $i+1 );
        @$array[$i,$j] = @$array[$j,$i];
    }
}

sub criarLinha {
    my $answer_str = shift;
    my $input_str = shift;
    my $repl = shift;
    return $answer_str =~ s/$repl/$input_str/gr;
}

sub templateLine {
    my $text = join("", <DATA>);
    my $label = shift;

    my $ret;
    if ($text =~ /__($label)__(.*?)(?=\n__|$)/gs) {
        $ret = $2;
    }
    chomp $ret;
    return $ret;
}

sub lertemplates {
    my $text = join("", <DATA>);
    my %funcoes;
    while ($text =~ /__(\w+)__(.*?)(?=\n__|$)/gs) {
        $funcoes{$1} = $2;
        # eval "sub $1 {aplicafuncao('$1', \@_)}";
        # print "$1\n$2\n\n";
    }
    return %funcoes;
}

__DATA__
__mkexer__

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<meta charset="UTF-8">
	<meta content="" name="author" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
	<meta content="" name="description">
	<meta content="" name="keywords">
<style type="text/css">
@media (min-width: 601px) {
	
BODY {margin:0;padding:0;background-color: #ffffff;}

#wrapper {
	background-color: #ffffff;
	padding: 10px;
	margin-left: auto;
    margin-right: auto;
    width: 50%;
	min-width:800px;
	font-family: verdana;
	font-size: 12pt;
	color: #000000;}
}

@media (max-width: 600px) {
BODY {margin:0;padding:0;background-color: #ffffff;}

#wrapper2 {
	background-color: #ffffff;
	padding: 10px;
	font-family: verdana;
	font-size: 12pt;
	color: #000000;}
}

img {
    max-width: 100%;
    height: auto;
}

FORM { margin: 5px 0 }


A:visited {color:#336699}
A:link {color:#336699}

.inputchange {width:120;height:17;border: solid 1px #6699cc}

</style>

<script language="javascript" type="text/javascript">
<!--
var score = 0;
var answer = new Array(§appl);
//Check and display score
function check(){
for(i=0;i<answer.length;i++){
   if(document.myform.elements[i].value.toLowerCase()==answer[i].toLowerCase()){
      score++;
   }
  }
  alert(score + " out of " + answer.length + ".");
  score = 0;
}
//Put the correct answers into all the fields
function show(){
for(i=0;i<answer.length;i++){
  document.myform.elements[i].value = answer[i];
  }
}
//-->
</script>
<!-- Go to www.addthis.com/dashboard to customize your tools -->
<script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-570f697842c7e31c"></script>


<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<script>
  (adsbygoogle = window.adsbygoogle || []).push({
    google_ad_client: "ca-pub-1174954976856705",
    enable_page_level_ads: true
  });
</script>
</head>


<body>

<div id="fb-root"></div>
<script>(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.async=true;
  js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.3";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>


<div style="background:#336699;text-align:center;margin:auto;"> </div>
<div id="wrapper">
<div id="wrapper2">
<div style="padding:10px;">
<div style="line-height: 150%;">
</div>
<!-- AddThis Button BEGIN -->
<!-- AddThis Button END -->
<div class="fb-like" data-layout="button_count" data-action="like" data-show-faces="false" data-share="false"></div>
<br /><br />
<!-- lpfg-resp -->
<!--ins class="adsbygoogle"
     style="display:block"
     data-ad-client="ca-pub-1174954976856705"
     data-ad-slot="5111566712"
     data-ad-format="auto"></ins-->
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
TOPIC:<strong> §enTopic (§plTopic)</strong>
<br><br>
<em>Complete the following translations, using the following words: <strong>§appl2</strong>.</em> 
<br/><hr/>
<!--EXERCISE START-->
<form name="myform" action="">

§linhas
<br>
<input type="button" value="Check Score" onClick="check();">
<input type="button" value="Show Solution" onClick="show();">
<input type="reset" value="Clear">
</form>
<br><br>
<a href="index.html">Back to list of exercises</a>


<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- lpfg-resp -->
<ins class="adsbygoogle"
     style="display:block"
     data-ad-client="ca-pub-1174954976856705"
     data-ad-slot="5111566712"
     data-ad-format="auto"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script><br /><br />
</div>
<br /><br />
</div>
</div>
</div>
</body>
</html>

__inputLine__<INPUT TYPE="text" VALUE="" class="inputchange">
__linha__
 §en = §pl<br><br>

__END__
=encoding utf8

=head1 NAME

mkvocabulary - Create a vocabulary exercises

=head1 SYNOPSIS
    perl mkvocabulary.pl x.vexe > index.html

=head1 DESCRIPTION

=head2 Input format

    Topic = The Weather = Clima
    It's very humid today. = Hoje é um [dia] muito [húmido].
    Arizona has a dry climate. = Arizona tem um [clima] seco.
    ...

=head1 AUTHOR

    Calafate, Renato

=head1 SEE ALSO

perl(1).

=cut

