import requests
import json
from requests.structures import CaseInsensitiveDict
from bs4 import BeautifulSoup
import pandas as pd
from tabulate import tabulate

"""
questo programma è un esempio di uso di API UMLS
è stato scritto da Sara Marceglia
"""

#ottenere in ticket granting ticket (8 ore)
urlTGT = "https://utslogin.nlm.nih.gov/cas/v1/api-key"
apiKey = "460790e8-6a77-48b8-97f7-4a42ef08cb3b"

#content-type: application/x-www-form-urlencoded'

headers = CaseInsensitiveDict()
headers["Content-Type"] = "application/x-www-form-urlencoded"

data = "apikey="+apiKey

respPOST = requests.post(urlTGT, headers = headers, data = data)

# RICERCA PER TERMINE

#passo 1 - ottenere ticket singolo
soup = BeautifulSoup(respPOST.text)
tag = soup.form
urlST = tag.attrs["action"]

headers = CaseInsensitiveDict()
headers["Content-Type"] = "application/x-www-form-urlencoded"

data = "service=http%3A%2F%2Fumlsks.nlm.nih.gov"

respPOST_ST = requests.post(urlST, headers = headers, data = data)
ST = respPOST_ST.text

#passo 2 - fare la ricerca
#searchTerm="Parkinson"
searchTerm = input("Insert search term: ")
urlGET = "https://uts-ws.nlm.nih.gov/rest/search/current?string="+searchTerm+"&ticket="+ST+"&pageNumber = 2"
respGET = requests.get(urlGET)
A = respGET.json()
B = A["result"]
respLIST = B["results"]
tab_LIST=pd.DataFrame(respLIST)
print(tabulate (tab_LIST,headers = ['CUI','Source Dictionary','URI','Concept Name'],tablefmt= 'fancy_grid'))

with open('UMLS_results.txt','w') as f:
    f.write(tabulate (tab_LIST,headers = ['CUI','Source Dictionary','URI','Concept Name'],tablefmt= 'fancy_grid'))

#RICERCA PER CODICE CUI

respPOST_ST2 = requests.post(urlST, headers = headers, data = data)
ST2 = respPOST_ST2.text

CUI="C3850024"
baseGET_CUI = " https://uts-ws.nlm.nih.gov/rest/content/current/CUI/"+CUI+"?"
addTicket = baseGET_CUI+"ticket="+ST2

respGET_CUI = requests.get(addTicket)
CUI_resp = respGET_CUI.json()
CUI_def = CUI_resp['result'] 
CUI_name = CUI_def['name']
B1 = [CUI_def['ui'],CUI_def['name']]
print(B1)