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->root) ];
  },
  sub (/**/) {
    [ $self->structure($self->descend($self->root, split '/', $_[1])) ];
  },
}

sub structure {
  my ($self, $data) = @_;
  if (ref($data) eq 'HASH') {
    return {
      columns => [ 'key', 'value' ],
      data => [ map +{ key => $_, value => $data->{$_} }, sort keys %$data ],
    };
  } elsif (blessed($data) and $data->isa('IO::All::Dir')) {
    return {
      columns => [ 'name', 'explore' ],
      data => [
        map +{ name => $_, explore => $self->link_to($_) }, keys %$data,
      ]
    };
  } else {
    die "Confused by $data";
  }
}

sub link_to {
  my ($self, $to) = @_;
  use HTML::Tags;
  my $html = join '', HTML::Tags::to_html_string(
    <a href="${to}/">, "Explore $to", </a>
  );
  return \$html;
}

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

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

sub render_el {
  my ($self, $whole, $part) = @_;
  if (ref($part) eq 'ARRAY') {
    return join(', ', @$part);
  }
  if (ref($part) eq 'HASH') {
    return $self->link_to($whole->{key});
  }
  return $part;
}

__PACKAGE__->run_if_script;
