#!/usr/bin/perl
use strict;
use warnings;
use JSON;

# Specify the path to your JSON file
my $json_file = 'json.dr';

# Read JSON data from the file
open my $json_fh, '<:encoding(UTF-8)', $json_file or die "Cannot open file: $!";
my $json_data = do { local $/; <$json_fh> };
close $json_fh;

# Parse JSON
utf8::encode($json_data);
my $data = decode_json($json_data);

# Generate HTML
my $html = generate_html($data);

# Specify the path to your output HTML file
my $output_file = 'index.html';

# Write HTML to the output file with UTF-8 encoding
open my $output_fh, '>:encoding(UTF-8)', $output_file or die "Cannot open file: $!";
print $output_fh $html;
close $output_fh;

# Function to generate HTML from JSON list of objects
sub generate_html {
    my ($data) = @_;

    my $html = <<'END_HTML';
<html>
<head>
  <meta charset="UTF-8">
  <title>JSON List to HTML</title>
</head>
<body>
END_HTML

    $html .= '<table border="1"><tr>';
    
    # Specify the attributes to be included in the table
    my @attributes = qw(name description versions guestos fileName downloadUrl createtime fileSize);

    # Create table header
    foreach my $attr (@attributes) {
        $html .= "<th>$attr</th>";
    }

    $html .= '</tr>';

    # Create table rows
    foreach my $item (@$data) {
        $html .= '<tr>';
        foreach my $attr (@attributes) {
            my $value = $item->{$attr};
            my $drfile = ".dr";
            if($attr eq "name") {
                $html .= "<td><a href=\"./$value$drfile\">$value</a></td>";
            }
            elsif($attr eq "fileName") {
                $html .= "<td><a href=\"./$value\">$value</a></td>";
            }
            else
            {
                $html .= "<td>$value</td>";
            }   	
	#<a href="./vzdump-qemu-224-2022_12_16-16_08_03.vma.zst">vzdump-qemu-224-2022_12_16-16_08_03.vma.zst</a>
        }
        $html .= '</tr>';
    }

    $html .= '</table>';
    $html .= '</body></html>';

    return $html;
}
