#!perl
use 5.23.8;
use strict;
use warnings;

# perl5120delta - 5.12.0 == Unicode 5.2
# perl5140delta - 5.14.0 == Unicode 6
# perl5160delta - 5.16.0 == Unicode 6.1
# perl5180delta - 5.18.0 == Unicode 6.2
# perl5200delta - 5.20.0 == Unicode 6.3
# perl5220delta - 5.22.0 == Unicode 7
# perl5240delta - 5.24.0 == Unicode 8
my %min_perl = (
  V5_2 => '5.012',
  V6_0 => '5.014',
  V6_1 => '5.016',
  V6_2 => '5.018',
  V6_3 => '5.020',
  V7_0 => '5.022',
  V8_0 => '5.023008', # placeholder for 5.024
);

my $MIN_AGE = 'V5_2';
my $MAX_AGE = 'V8_0';

use HTTP::Tiny;
use JSON;
use List::Util qw(maxstr);
use Unicode::UCD 'charprop';

my $res = HTTP::Tiny->new->get(
  "https://raw.githubusercontent.com/iamcal/emoji-data/master/emoji.json",
);

die "error: $res->{content}" unless $res->{success};

my $json = $res->{content}; # XXX: Can we really assume this is ASCII?

my $data = JSON->new->decode($json);

my %emoji;

for my $char (sort { $a->{short_name} cmp $b->{short_name} } @$data) {
  my @points  = split /-/, ($char->{variations}->[0] || $char->{unified});

  my $max_age = maxstr map {; charprop( hex("0x$_"), "Age") } @points;
  if ($max_age lt $MIN_AGE) { $max_age = $MIN_AGE }
  if ($max_age gt $MAX_AGE) { die "can't handle unicode age $max_age\n" }

  my $perl = $min_perl{ $max_age };
  die "can't handle $max_age\n" unless $perl;

  my $str = join q{}, map {; "\\x{$_}" } @points;

  for my $name (@{ $char->{short_names} }) {
    $emoji{$perl}{$name} = $str;
  }
}

my $output = "my %hash;\n";

$output .= qq{  \$hash{simple_smile} = "\\x{1F642}";\n};

for my $perl (sort keys %emoji) {
  $output .= "if (\$] >= $perl || ! \$ENV{SLACKEMOJI_STRICT}) {\n";
  $output .= qq{  \$hash{"$_"} = "$emoji{$perl}{$_}";\n}
    for sort keys %{ $emoji{$perl} };
  $output .= "}\n";
}

$output .= "return \\%hash;\n";

print $output;
