import csv, requests, time, logging

def write_csv_from_list(cID, wrapper_list):
# takes ID and csv wrapper to write file with ID name
# need to use different paths, can add in folder structure to cID field
    with open('./%s' % cID, 'w', encoding='utf-8') as f:
        csv.writer(f).writerows(wrapper_list)

def read_csv_to_list_wrapper(path):
    wrapper = []
    with open(path, 'r', encoding='utf-8') as f:
        csv_reader = csv.reader(f)
        for row in csv_reader:
            if row == []:
                # handling for blank rows, which exist for some reason?
                pass
            else:
                wrapper.append(row)
    return wrapper

def add_ishare_to_wrapper(alma_wrapper):
    call_heading = 'Permanent Call Number'
    alma_wrapper[0].append('# in IShare')
    total_entries = len(alma_wrapper) - 1
    logname = 'primo_query.log'

    logging.basicConfig(filename=logname,
        filemode='a',
        format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
        datefmt='%H:%M:%S',
        level=logging.DEBUG)

    logging.info('Primo_http_errors')

    # this isn't actually as bad as it looks
    for index, column_heading in enumerate(alma_wrapper[0]):
        if (column_heading == call_heading):
            for row_index, row in enumerate(alma_wrapper[1:]):
                time.sleep(15/10)
                primo_results = primo_api(row[index])
                if (primo_results.status_code == 200):
                    row.append(how_many_ishare(primo_results.json()))
                else:
                    logging.error('something died at ' + row[index])
                    logging.error(primo_results.status_code)
                    logging.error(primo_results.text)
                    print('something died at ' + row[index])
                    print(primo_results.status_code)
                    print(primo_results.text)
                    continue
                print('almost there!: ' + str(row_index + 1) + '/' + str(total_entries))
            break

def how_many_ishare(primo_results):
    for c in primo_results['facets']:
        if (c['name'] == 'institution'):
            return len(c['values'])

def is_available_ishare(call_number):
    # returns 1 if available in IShare, 0 if not
    primo_results = primo_api(call_number).json()
    if (not primo_results['docs'][0]['delivery']['almaInstitutionsList']):
        return 0
    else:
        return 1

def inst_code(primo_results):
    return primo_results['docs'][0]['delivery']['almaInstitutionsList'][0]['instCode']

def availability_status(primo_results):
    return primo_results['docs'][0]['delivery']['almaInstitutionsList'][0]['availabilityStatus']

def primo_api(query):
    # takes primo query term and searches all ishare institutions, returns response. seems to work well using call number field

    api_key = <api_key>
    url = 'https://api-na.hosted.exlibrisgroup.com/primo/v1/pnxs?vid=01CARLI_UIS:CARLI_UIS&tab=NewDiscoveryNetwork&scope=NewDiscoveryNetwork&q=any,contains,'
    assembled = url + query + api_key
    response = requests.get(assembled)
    return response

if __name__ == "__main__":
    alma_wrapper = read_csv_to_list_wrapper('./test_csv.csv')

    add_ishare_to_wrapper(alma_wrapper)

    write_csv_from_list('api_list_ishare.csv', alma_wrapper)

