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->pretty
}

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') {
    if (keys %$data > 1
        and values %$data == grep ref($_) eq 'HASH', values %$data) {
      my %tmp;
      $tmp{join '|', keys %$_} = 1 for values %$data;
      if (keys %tmp == 1) {
        $data->{$_}->{name} ||= $_ for keys %$data;
        my @cols = grep $_ ne 'name', sort keys %{(values %$data)[0]};
        unshift @cols, 'name';
        return {
          columns => \@cols,
          show_columns => 1,
          data => [ @{$data}{sort keys %$data} ],
        }
      }
    }
    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') {
    if ($whole->{key}) {
      return $self->link_to($whole->{key})
    }
    $part = '(complex)';
  }
  use HTML::Tags;
  return $part =~ /\n/ ? (<pre>, $part, </pre>) : $part;
}

__PACKAGE__->run_if_script;
