package TB_Temp_Packname;

use Web::Simple;
use Scalar::Util qw(blessed);
use IO::All;
use JSON;

has root => (is => 'lazy');

has json => (is => 'lazy');

sub _build_root {
  io->dir("/home/matthewt/tmp/introspection-data/host/services-dev/stable/node/host/")
}

sub _build_json {
  JSON->new->relaxed
}

sub dispatch_request {
  my ($self) = @_;
  sub () {
    response_filter {
      ref($_[0][0]) eq 'HASH' ? $self->render_table($_[0][0]) : $_[0]
    }
  },
  sub (/**/) {
    $self->structure($self->descend($self->root, split '/', $_[1]));
  },
}

sub structure {
  my ($self, $data) = @_;
  if (ref($data) eq 'HASH') {
    $data = [ @{$data}{sort keys %$data} ];
    my @cols = sort keys %{$data->[0]};
    return [ {
      columns => \@cols,
      data => $data,
    } ];
  } else {
    die "Confused by $data";
  }
}

sub descend {
  my ($self, $target, @path) = @_;
  return $target unless @path;
  my $step = shift @path;
  if (blessed($target) and $target->isa('IO::All::File')) {
    $target = $self->json->decode(scalar $target->all);
  }
  $self->descend($target->{$step}, @path);
}

sub render_table {
  my ($self, $data) = @_;
  use HTML::Tags;
  my @rows = (
    $data->{columns},
    map [ @{$_}{@{$data->{columns}}} ], @{$data->{data}}
  );
  [ 200, [ 'Content-type' => 'text/html' ], [
    HTML::Tags::to_html_string(
      <html>, <body>, "\n",
      <table>, "\n",
        (map {;
          '  ', <tr>,
            (map { <td>, $self->render_el($_), </td> } @$_),
          </tr>, "\n"
        } @rows),
      </table>, "\n",
      </body>, </html>, "\n",
    )
  ] ];
}

sub render_el { ref($_[1]) eq 'ARRAY' ? join(', ', @{$_[1]}) : $_[1] }

__PACKAGE__->run_if_script;
