use Modern::Perl;
use File::Slurper qw(read_dir read_text write_text read_binary);
use Mojo::JSON qw(decode_json);
use Mojo::DOM;
use Mojo::Util qw(url_escape);
use Encode qw(decode_utf8 encode_utf8);

my $galleries_dir = 'gallery';
my $wiki_dir = 'wiki';

main();

sub main {
  my $md = "# Galleries\n\n";
  for my $dir (
    sort {
      my ($year_a, $title_a) = split(/-/, $a, 2);
      my ($year_b, $title_b) = split(/-/, $b, 2);
      return ($year_b <=> $year_a || $title_a cmp $title_b);
    } grep {
      -d "$galleries_dir/$_"
    } read_dir($galleries_dir)) {
    gallery($dir);
    my $name = decode_utf8($dir);
    my $url = url_escape($dir);
    $md .= "* [$name]($url/index)\n";
    for my $file (read_dir("$galleries_dir/$dir/imgs")) {
      if (not -e "$wiki_dir/$dir/$file") {
        link "$galleries_dir/$dir/imgs/$file", "$wiki_dir/$dir/$file"
            or die "Cannot rename $galleries_dir/$dir/imgs/$file to $wiki_dir/$dir/$file: $!";
      }
    }
  }
  write_text("$wiki_dir/galleries.md", $md);
}

sub gallery_title {
  my $dir = shift;
  $dir =~ s/-/ /g;
  return join(' ', map {ucfirst} split(' ', $dir));
}

sub gallery {
  my $dir = shift;
  if (not -r "$galleries_dir/$dir/data.json") {
    die "This gallery does not contain a data.json file like the one created by sitelen-mute or fgallery\n";
  }
  my $bytes = read_binary("$galleries_dir/$dir/data.json");
  if (not $bytes) {
    die "Cannot read the data.json file in this gallery\n";
  }
  my $data;
  eval { $data = decode_json $bytes };
  warn "decode_json: $@" if $@;
  if ($@ or not %$data) {
    die "Cannot decode the data.json file in this gallery\n";
  }
  say $dir;
  mkdir "$wiki_dir/$dir";
  my $md = "";
  if (-r "$galleries_dir/$dir/index.html") {
    my $dom = Mojo::DOM->new(read_text("$galleries_dir/$dir/index.html"));
    my $title = $dom->at('*[itemprop="name"]');
    $title = $title ? $title->text : gallery_title($dir);
    $md .= "# $title\n\n";
    my $description = $dom->at('*[itemprop="description"]');
    $md .= $description->text . "\n\n" if $description;
  } else {
    $md = "# " . gallery_title($dir) . "\n\n";
  }
  for my $image (@{$data->{data}}) {
    $md .= join("<br>\n", grep /\S/, @{$image->{caption}}) . "\n\n" if $image->{caption};
    my $src = $image->{img}->[0];
    $src =~ s/^imgs\///;
    $src = url_escape(encode_utf8($src));
    $md .= "![]($src)\n\n";
  }
  write_text("$wiki_dir/$dir/index.md", $md);
}