#!/usr/bin/env perl

my $copyright= <<'COPYRIGHT';
# Copyright 2023 by Christian Jaeger <ch@christianjaeger.ch>
# Published under the same terms as perl itself
COPYRIGHT

use strict;
use utf8;
use warnings;
use warnings FATAL => 'uninitialized';
use experimental 'signatures';

#use Chj::ruse;
#use Chj::Backtrace; 
#use FP::Show; use FP::Repl; use FP::Repl::Trap; #

my $glob = "resources/merged/elements/*.json";
my $elements = "includes/ahtml_elements_include.rs";

sub usage {
    print STDERR map{"$_\n"} @_ if @_;
    print "$0

   Regenerates the file $elements from the file names $glob
";
exit (@_ ? 1 : 0);
}

usage if @ARGV;


my @names = map {
    s{.*/}{};
    s{\..*}{};
    $_
} glob $glob;

open my $out, ">", $elements or die "$elements: $!";

print $out "// GENERATED by $0, DO NOT EDIT

" or die $!;

for my $name (@names) {
    my $ucname = uc $name;
    # Wrap every individual global with lazy_static because otherwise
    # we run into a macro expansion recursion limit, and while that
    # can be relaxed, why not take this pain out of the equation.
    print $out "lazy_static!{
    pub static ref ${ucname}_META: &'static ElementMeta = METADB.elementmeta.get(\"$name\").unwrap();
}
" or die $!;
}

print $out "
impl HtmlAllocator {
" or die $!;

sub printel($name) {
    my $ucname = uc $name;
    print $out
        "    #[allow(dead_code)]
    pub fn $name(&self,
             attr: impl ToASlice<(KString, KString)>,
             body: impl ToASlice<Node>
    ) -> Result<AId<Node>>
    {
        self.element(\&${ucname}_META, attr, body)
    }
" or die $!
}

printel $_ for @names;

print $out "}
" or die $!;

close $out or die $!;
