#!/usr/bin/env perl
use Modern::Perl '2014';
use experimental 'switch';
use lib './lib';
use Path::Tiny;
use DOM::Tiny;
use MGH_Biostat::Locale::PO;
use JSON::XS;
use Encode;

my $pos = [];

# generate a header
push @$pos, MGH_Biostat::Locale::PO->new(
    -msgid => '',
    -msgstr =>
      "Project-Id-Version: PACKAGE VERSION\n" .
      "PO-Revision-Date: YEAR-MO-DA HO:MI +ZONE\n" .
      "Last-Translator: <none yet>\n" .
      "Language: \n" .
      "MIME-Version: 1.0\n" .
      "Content-Type: text/plain; charset=UTF-8\n" .
      "Content-Transfer-Encoding: 8bit\n",
    -comment =>
      "TRhIP is an expert system for travelers\n" .
      "Copyright (C) REMorse\n" .
      "Ricky Morse <remorse\@mgh.harvard.edu>, 2016\n",
);

my $seen       = {};
my $addtl_refs = {};

# go through the templates
foreach my $file ( 'questions.tmpl', 'recommendations.tmpl' ) {
    my $dom = DOM::Tiny->new()->xml(0)->parse( '<div>' . path( 'templates/' . $file )->slurp_utf8 . '</div>' );
    $dom->find('*[data-gettext]')->each(
        sub {
            my $id    = $_->attr('id');
            my $msgid = $_->content();
            for ($msgid) { s/\A\s+//; s/\s+\z//; }
            my $key       = $_->attr('data-gettext') || '';
            my $comment   = $_->attr('data-gettext-comment');
            my $reference = $file . '#' . $id . ( $key ne '' ? '|' . $key : '' );
            if ( !defined( $seen->{$msgid} ) ) {
                push @$pos, MGH_Biostat::Locale::PO->new( -msgid => $msgid, -msgstr => '', -reference => $reference, -automatic => $comment );
                $seen->{$msgid} += 1;
            }
            else {
                push @{ $addtl_refs->{$msgid} }, $reference;
            }
        }
    );
}

foreach (@$pos) {
    if ( defined( $addtl_refs->{ $_->msgid } ) ) {
        my $reference = $_->reference;
        unshift @{ $addtl_refs->{ $_->msgid } }, $reference;
        $_->reference( join( "\n" => @{ $addtl_refs->{ $_->msgid } } ) );
    }
}

# go through the dynamic file
{
    my $file           = path('templates/dynamic.strings')->openr_utf8;
    my $current_stanza = '';
    while (<$file>) {
        chomp;
        next if m/^#/;
        next unless m/\S/;
        if (m/^\[(\w+)\]/) {
            $current_stanza = $1;
            next;
        }

        my ( $key, $rest ) = split /\s*:\s*/, $_, 2;
        my $obj = decode_json( encode( 'utf-8', $rest ) );
        my $reference = 'dynamic.strings#' . $current_stanza . '."' . $key . '"';

        given ($current_stanza) {
            when ('static') {
                push @$pos, MGH_Biostat::Locale::PO->new( -msgid => $key, -msgstr => $obj->{'string'}, -reference => $reference, -automatic => $obj->{'comment'} );
            }
            when ('plural') {
                push @$pos, MGH_Biostat::Locale::PO->new( -msgid => $obj->{'single'}, -msgid_plural => $obj->{'plural'}, -msgstr_n => [ '', '' ], -reference => $reference, -c_format => 1, -automatic => $obj->{'comment'} );
            }
            when ('countries') {
                push @$pos, MGH_Biostat::Locale::PO->new( -msgid => $key, -msgctxt => 'Menu',              -msgstr => "", -reference => $reference, -automatic => "This will be displayed in the destination selection menu.\nEnglish equivalent: " . $obj->{'menu'} );
                push @$pos, MGH_Biostat::Locale::PO->new( -msgid => $key, -msgctxt => 'List',              -msgstr => "", -reference => $reference, -automatic => "This will be displayed when listing countries in a non-prepositional context.\nThis may require articles or other changes to make it read well.\nEnglish equivalent: " . $obj->{'list'} );
                push @$pos, MGH_Biostat::Locale::PO->new( -msgid => $key, -msgctxt => 'Is present (in _)', -msgstr => "", -reference => $reference, -automatic => "This will be used in the sentence 'Malaria is present in ...', although there may be several countries listed. This may involve declension.\nEnglish equivalent: " . $obj->{'malaria'} );
            }
        }
    }
}

# save the file
MGH_Biostat::Locale::PO->save_file_fromarray( 'po/trhip.pot', $pos, 'utf8' );

__END__
# commands to create po files from the pot file
# for l in "langs"; do GETTEXTCLDRDIR=1 msginit --no-wrap -l ${l}; done
GETTEXTCLDRDIR=1 msginit --no-wrap -l en-US
GETTEXTCLDRDIR=1 msginit --no-wrap -l fr-FR
GETTEXTCLDRDIR=1 msginit --no-wrap -l es
GETTEXTCLDRDIR=1 msginit --no-wrap -l pt-BR
GETTEXTCLDRDIR=1 msginit --no-wrap -l ht
GETTEXTCLDRDIR=1 msginit --no-wrap -l bn
GETTEXTCLDRDIR=1 msginit --no-wrap -l hi
GETTEXTCLDRDIR=1 msginit --no-wrap -l zh-CN
GETTEXTCLDRDIR=1 msginit --no-wrap -l ar

# commands to update the po files
for f in `ls *.po`; do msgmerge --update --no-wrap --backup=off ${f} trhip.pot; done