#!/usr/bin/env perl
use Modern::Perl '2014';
use experimental 'switch';
use Data::Dumper;
use Path::Tiny;
use LWP::Simple;
use JSON::XS;
use Encode;
use lib './lib';

$Data::Dumper::Terse = 1;

$Data::Dumper::Sortkeys = \&dd_sort;

my $base_url     = 'http://www.unicode.org/repos/cldr-aux/json/26/';
my $cldr_version = "26";

# locales are passed on the command line
foreach my $tag (@ARGV) {
    my $orig_tag = $tag;
    if ( $tag eq 'zh-CN' ) { $tag = 'zh'; }

    # we want to get two pieces of information.
    # 1. the character orientation, located in
    #      main/<tag>/layout.json [ main/<tag>/layout/orientation/characterOrder ]
    # 2. the list information, located in
    #      main/<tag>/listPatterns.json [ main/<tag>/listPatterns/listPattern-type-standard ]

    # we need to special case the 'ht' tag, because it isn't in CLDR properly.

    my $data = {};

    $data->{'cldr_version'} = $cldr_version;

    if ( $tag eq 'ht' ) {
        $data->{'orientation'} = "left-to-right";
        $data->{'list'}        = {
            2        => "{0} ak {1}",
            'start'  => "{0}, {1}",
            'middle' => "{0}, {1}",
            'end'    => "{0} ak {1}",
        };
    }
    else {
        my $ojson = get( $base_url . "main/$tag/layout.json" );
        my $odata = decode_json($ojson);
        $data->{'orientation'} = $odata->{'main'}{$tag}{'layout'}{'orientation'}{'characterOrder'} // "left-to-right";

        my $ljson = get( $base_url . "main/$tag/listPatterns.json" );
        my $ldata = decode_json( encode( 'utf-8', $ljson ) );
        $data->{'list'} = $ldata->{'main'}{$tag}{'listPatterns'}{'listPattern-type-standard'};
    }

    my $clean_tag = ( ( $orig_tag =~ s/[^A-Za-z0-9_-]//gr ) =~ s/-/_/gr );

    my $package = 'MGH_Biostat::Locale::DB::' . $clean_tag;

    my $out = "package $package;\nuse warnings; use strict;\n\n";
    foreach my $key (qw(cldr_version orientation list)) {
        $out .= 'our $' . $key . ' = ' . ( Dumper( $data->{$key} ) =~ s/\n$/;\n/mr ) . "\n";
    }
    $out .= "1;\n";

    my $path = ( $package =~ s/::/\//gr );
    $path = './lib/' . $path . '.pm';
    path($path)->spew_utf8($out);
    say "$tag written";
}

sub dd_sort {
    my $ref = shift;
    if ( defined( $ref->{'cldr_version'} ) ) {

        # main level
        return [ qw(cldr_version orientation list) ];
    }
    elsif ( defined( $ref->{'2'} ) ) {

        # list
        return [ qw(2 start middle end) ];
    }
    else {
        return [ sort keys %$ref ];
    }
}