#!/usr/bin/env perl

use Mojolicious::Lite -signatures;
use JSON::MaybeXS qw(decode_json);
use Scalar::Util qw(reftype);

helper render_data => sub ($c, $value) {

    return '' unless defined $value;

    # scalar
    return $c->escape($value) unless ref $value;

    my $type = reftype($value) // '';

    # hash
    if ($type eq 'HASH') {

        my $html = '';

        $html .= $c->tag(table => {class => 'kv'}, sub {

            my $rows = '';

            for my $key (sort keys %$value) {

                $rows .= $c->tag(tr =>
                    $c->tag(th => $key)
                  . $c->tag(td => $c->render_data($value->{$key}))
                );
            }

            return $rows;
        });

        return $html;
    }

    # array
    if ($type eq 'ARRAY') {

        return $c->tag(ul =>
            join '',
                map { $c->tag(li => $c->render_data($_)) }
                @$value
        );
    }

    return $c->tag(pre => "$value");
};

my $json = <<'JSON';
{
  "timestamp":"2022-04-15T18:25:15.364891+0200",
  "version":"4.17.0pre1-GIT-a0f12b9c80b",
  "sessions":{
    "3639217376":{
      "username":"johndoe",
      "uid":1000,
      "gid":1000,
      "hostname":"127.0.0.1"
    }
  },
  "tcons":{
    "3813255619":{
      "service":"homes",
      "machine":"127.0.0.1"
    }
  }
}
JSON

my $data = decode_json($json);

get '/' => sub ($c) {

    $c->stash(data => $data);

    $c->render(template => 'index');
};

app->start;

__DATA__

@@ layouts/default.html.ep
<!doctype html>
<html>
<head>
<meta charset="utf-8">

<title>Samba Status</title>

<style>

body {
    font-family:sans-serif;
    margin:2em;
}

table {
    border-collapse:collapse;
    margin:.5em 0;
}

th,td {
    border:1px solid #bbb;
    padding:.35em .7em;
    vertical-align:top;
}

th {
    background:#eee;
    text-align:left;
}

.kv {
    width:100%;
}

section {
    margin-bottom:2em;
}

code {
    background:#eee;
    padding:2px 4px;
}

</style>

</head>

<body>

%= content

</body>
</html>

@@ index.html.ep

% my $d = stash('data');

<h1>Samba Status</h1>

<section>

<h2>General</h2>

<table>

<tr>
<th>Timestamp</th>
<td><%= $d->{timestamp} %></td>
</tr>

<tr>
<th>Version</th>
<td><%= $d->{version} %></td>
</tr>

</table>

</section>

<section>

<h2>Sessions</h2>

% for my $id (sort keys %{$d->{sessions}}) {

<h3>Session <%= $id %></h3>

%== render_data($d->{sessions}{$id})

% }

</section>

<section>

<h2>TCONS</h2>

% for my $id (sort keys %{$d->{tcons}}) {

<h3>TCON <%= $id %></h3>

%== render_data($d->{tcons}{$id})

% }

</section>