#!/usr/local/bin/python

import sys
import json
import urllib2

if len(sys.argv) < 2:
	print "Usage: process_list_api <FILE> <API_BASE_URL=http://api.openconsortium.eu/cordis/1>"
	print "  Example: process_list_api items.json"
	print "  Calls the Cordis API with the list of RCNs so they get stored in the API's cache" 
else:

	json_data = open(sys.argv[1])
	data = json.load(json_data)

	api_base = 'http://api.openconsortium.eu/cordis/1'
	if len(sys.argv) == 3:
		api_base = sys.argv[2]

	method = '/projects/'

	success = 0
	for rcn in data:
		try:
			url = api_base + method + str(rcn)
			response = urllib2.urlopen(url)
			print "Called " + url
			success += 1
		except IOError as e:
			print "I/O error({0}): {1}".format(e.errno, e.strerror)
			pass
		except:
			print "Unexpected error:", sys.exc_info()[0]
			pass

	print "Successfully processed " + str(success) + "/" + str(len(data)) + " projects using API " + api_base

	json_data.close()