#!/usr/bin/perl

@callNumberTypes = `cat /opt/folio/config/callNumberTypes`;
foreach $row (@callNumberTypes) {
	($id,$name) = split(/\|/,$row);
	$callNumberTypeName{$id} = $name;
}
$gd2 = "eb1837d4-3f8e-45c1-8680-cd4e7fe02288";
$headers = `cat /opt/folio/config/headers`; chomp($headers); 
@mtypes = `cat /opt/folio/config/mtypes`;
foreach $row (@mtypes) {
	($id,$name) = split(/\|/,$row);
	$mtypeName{$id} = $name;
}
$url = `cat /opt/folio/config/url`; chomp($url);

use JSON;

open (wFile, ">:encoding(UTF-8)", "shelfList.txt");

$jsonA = `curl -s -X GET -G $headers -d 'limit=1000' $url/holdings-storage/holdings?query=permanentLocationId=="$gd2"`;
$hashA = decode_json $jsonA;
for ( @{$hashA->{holdingsRecords}} ) {
	$counter++;
	$callNumber = $_->{callNumber};
	$callNumberTypeId = $_->{callNumberTypeId};
	$id = $_->{id};
	$instanceId = $_->{instanceId};
	$jsonB = `curl -s -X GET -G $headers $url/instance-storage/instances/$instanceId`;
	$hashB = decode_json $jsonB;
	$title = $hashB->{title};
	$jsonC = `curl -s -X GET -G $headers -d 'limit=0' $url/item-storage/items?query=holdingsRecordId==$id`;
	$hashC = decode_json $jsonC;
	$totalItems = $hashC->{totalRecords};
	if ($totalItems > 0) {
		$jsonD = `curl -s -X GET -G $headers -d 'limit=$totalItems' $url/item-storage/items?query=holdingsRecordId==$id`;
		$hashD = decode_json $jsonD;
		for ( @{$hashD->{items}} ) {
			$barcode = $_->{barcode};
			$materialTypeId = $_->{materialTypeId};
			print wFile "$callNumber|$callNumberTypeName{$callNumberTypeId}|$mtypeName{$materialTypeId}|$barcode|$title|\n";
			print "$counter|$callNumber|$callNumberTypeName{$callNumberTypeId}|$mtypeName{$materialTypeId}|$barcode|$title|\n";
		}
	} else {
		print wFile "$callNumber|$callNumberTypeName{$callNumberTypeId}|n/a|n/a|$title|\n";
		print "$counter|$callNumber|$callNumberTypeName{$callNumberTypeId}|n/a|n/a|$title|\n";
	}
}

close(wFile);