#!/usr/bin/env perl

use strict;
use warnings;

my $underscore_test = shift @ARGV || "";
if (!-d $underscore_test) {
    print <<_END_;
Usage:

    testify ./underscore/test

    # Should look something like:
    arrays.js
    chaining.js
    collections.js
    functions.js
    index.html
    objects.js
    speed.js
    utility.js
    vendor

_END_
    if ($underscore_test) {
        die "!: Not a directory: $underscore_test\n"
    }
    exit;
}

chdir $underscore_test or die "!: $!";

my @js = <*.js>;

for my $file (@js) {
    open my $fh, '<', $file or die "!: $!";
    my $tests = join "", <$fh>;
    my @tests = $tests =~ m/
        ^(\s{2}test\(.*?
        ^\s{2}}\);)$
    /mgxs;
    close $fh;
    next unless @tests;
    print "$file: ", scalar(@tests), "\n";
    my $underscore_name = "underscore_$file";
    $underscore_name =~ s/.js$//;
    my $go_file = "${underscore_name}_test.go";
    $go_file =~ s/.js$/.go/;
    open $fh, '>', $go_file or die "!: $!";

    $fh->print(<<_END_);
package otto

import (
	"testing"
)

_END_

    my $count = 0;
    for my $test (@tests) {
        $test =~ s/`([^`]+)`/<$1>/g;
        my ($name) = $test =~ m/^\s*test\(['"]([^'"]+)['"]/;
        $fh->print(<<_END_);
// $name
func Test_${underscore_name}_$count(t *testing.T) {
    tt(t, func(){
	    test := underscoreTest()

	    test(`
$test
        `)
    })
}

_END_
        $count++;
    }
}

#  test('#779 - delimeters are applied to unescaped text.', 1, function() {
#    var template = _.template('<<\nx\n>>', null, {evaluate: /<<(.*?)>>/g});
#    strictEqual(template(), '<<\nx\n>>');
#  });
