#!/usr/bin/perl

use CGI;
$query = new CGI;
$uri = $query->param("discogsURL");
@parse1 = split(/\//,$uri);
($releaseId,$dreck) = split(/-/,$parse1[4]);

$userAgent = "DiscogsAtDrew/0.1 +https://tipple.drew.edu/discogs";

$json = `curl -s https://api.discogs.com/releases/$releaseId --user-agent "$userAgent"`;

use JSON;

$hash = decode_json $json;

$artistId = 0;
for ( @{$hash->{artists}} ) {
        $name = $_->{'name'};
        $artist .= qq[<tr><td>artist</td><td class="v12">];
        $artist .= qq[<input name="name$artistId" type="radio" value="Personal Name" checked>person   ];
        $artist .= qq[<input name="name$artistId" type="radio" value="Corporate Name">group   ];
        $artist .= qq[<input name="artist" size="75" type="text" value="] . $_->{'name'} . qq[">   ];
        $artist .= qq[<input name="artist$artistId" type="radio" value="Composer">composer   ];
        $artist .= qq[<input name="artist$artistId" type="radio" value="Performer" checked>performer</td></tr>];
        $artistId++;
}
for ( @{$hash->{extraartists}} ) {
        $name = $_->{'name'};
        if ($artist =~ /$name/) {
                $note2self = "do nothing";
        } else {
                $artist .= qq[<tr><td>artist</td><td class="v12">];
                $artist .= qq[<input name="name$artistId" type="radio" value="Personal Name" checked>person   ];
                $artist .= qq[<input name="name$artistId" type="radio" value="Corporate Name">group   ];
                $artist .= qq[<input name="artist" size="75" type="text" value="] . $_->{'name'} . qq[">   ];
                $artist .= qq[<input name="artist$artistId" type="radio" value="Composer">composer   ];
                $artist .= qq[<input name="artist$artistId" type="radio" value="Performer" checked>performer</td></tr>];
                $artistId++;
        }
}

for ( @{$hash->{labels}} ) {
        $name = $_->{'name'};
        $catno = $_->{'catno'};
        $vendorTCN = qq[<tr><td>label</td><td><input name="label" size="125" type="text" value="$name $catno"></td></tr>];
}
$title = qq[<tr><td>title</td><td><input name="title" size="125" type="text" value="] . $hash->{'title'} . qq["></td></tr>];


$fcn = qq[<tr><td valign="top">contents</td><td><textarea cols="115" name="fcn" rows="5">];
for ( @{$hash->{tracklist}} ) {
        $fcn .= $_->{'title'} . "--";
}
$fcn =~ s/--$//;
$fcn =~ s/"//g;
$fcn .= qq[</textarea></td></tr>];

$year = $hash->{'year'};
if ($year == 0) {
        $year = qq[<tr><td>year</td><td><input name="year" size="125" type="text" value=""></td></tr>];
} else {
        $year = qq[<tr><td>year</td><td><input name="year" size="125" type="text" value="] . $hash->{'year'} . qq["></td></tr>];
}