#!/bin/perl
#
# Extract supported divecomputers from libdivecomputer source
#
# Usage:
#
# parse-descriptor.pl <outfile>
#
# depending on suffix of the outfile it creates the right content for
# either a text file or and html file
use Carp;

#set command line arguments
my $outfi = $ARGV[0];
my ($type) = $outfi =~ /\.([^.]+)$/;

my $infi = "libdivecomputer/src/descriptor.c";

open(my $fh, "<", $infi) || croak "can't open $infi: $!";
open(STDOUT, ">", $outfi) || croak "can't open $outfi: $!";

my $commentStart = "# ";
my $commentEnd = "";
my $first_mod_txt = ": ";
my $next_mod_txt = ", ";
my $next_vendor_txt = "\n";
my $first_vendor_txt = "";

if ($type eq "html") {
	$commentStart = "<!-- ";
	$commentEnd = " -->";
	$first_mod_txt = "</dt><dd><ul>\n\t    <li>";
	$next_vendor_txt = "</li></ul>\n    </dd>\n    <dt>";
	$first_vendor_txt = "<dl><dt>";
} elsif ($type eq "md" ) {
	$commentStart = "[//]: # '";
	$commentEnd = "'";
	$first_mod_txt = ":\n- ";
	$next_mod_txt = "\n- ";
	$next_vendor_txt = "\n\n## ";
	$first_vendor_txt = "\n\n## ";
}

printf("%s This file is automatically generated, please edit scripts/parse-descriptor.pl%s\n", $commentStart, $commentEnd);

my $lastVend = "";
my $lastMod = "";
my @descriptors = ();
while (<$fh>) {
	if (/^\s*{\s*"([^\,]*)"\s*,\s*"([^\,]*)"\s*,\s*([^\,]*).*}/) {
		push(@descriptors, "$1,$2");
	}
}
my @sortedDescriptors = sort @descriptors;
foreach (@sortedDescriptors) {
	($vend, $mod) = split(',', $_);
	next if ($vend eq $lastVend && $mod eq $lastMod);
	if ($vend eq $lastVend) {
		printf("%s%s", $next_mod_txt, $mod);
	} else {
		if ($lastVend lt "Seabaer" && $vend gt "Seabaer") {
			printf("%s%s%s%s", $next_vendor_txt, "Seabaer", $first_mod_txt, "T1, H3, HUDC");
		}
		if ($lastVend lt "Uemis" && $vend gt "Uemis") {
			printf("%s%s%s%s", $next_vendor_txt, "Uemis", $first_mod_txt, "Zürich SDA");
		}
		if ($lastVend eq "") {
			printf("%s%s%s%s", $first_vendor_txt, $vend, $first_mod_txt, $mod);
		} else {
			printf("%s%s%s%s", $next_vendor_txt, $vend, $first_mod_txt, $mod);
		}
	}
	$lastVend = $vend;
	$lastMod = $mod;
}
if ($type eq "html") {
    print("</li>\n\t</ul>\n    </dd>\n</dl>");
}
close $fh;