import os
from fastapi import FastAPI, Form
import logging
from starlette.staticfiles import StaticFiles
from starlette.responses import FileResponse
from eu.dnetlib.es_connector import DLIESConnector
import sys
from eu.dnetlib.metrics_utils import metrics 
from eu.dnetlib.metricsMiddleware import PrometheusMiddleware

_CURDIR = os.path.dirname(os.path.abspath(__file__))

app = FastAPI()

app.mount('/static', StaticFiles(directory=os.path.join(_CURDIR, 'static' )))
base_dnet_url = "http://aggregator-dli.openaire.eu/dli/"
pid_resolver = {
    "pdb": "http://www.rcsb.org/pdb/explore/explore.do?structureId=%s",
    "ncbi-n": "http://www.ncbi.nlm.nih.gov/gquery/?term=%s",
    "pmid": "http://www.ncbi.nlm.nih.gov/pubmed/%s",
    "pmcid": "http://www.ncbi.nlm.nih.gov/pmc/articles/%s",
    "pubmedid": "http://www.ncbi.nlm.nih.gov/pubmed/%s",
    "doi": "http://dx.doi.org/%s",
    "genbank": "http://www.ncbi.nlm.nih.gov/nucest/%s?report=genbank",
    "nuccore": "http://www.ncbi.nlm.nih.gov/nucest/%s?report=genbank",
    "swiss-prot": "http://www.ncbi.nlm.nih.gov/nucest/%s?report=genbank",
    "arrayexpress": "http://www.ncbi.nlm.nih.gov/nucest/%s?report=genbank",
    "biomodels": "http://www.ncbi.nlm.nih.gov/nucest/%s?report=genbank",
    "bmrb": "http://www.ncbi.nlm.nih.gov/nucest/%s?report=genbank",
    "ena": "http://www.ncbi.nlm.nih.gov/nucest/%s?report=genbank",
    "geo": "http://www.ncbi.nlm.nih.gov/nucest/%s?report=genbank",
    "ensembl": "http://www.ncbi.nlm.nih.gov/nucest/%s?report=genbank",
    "mgi": "http://www.ncbi.nlm.nih.gov/nucest/%s?report=genbank",
    "bind": "http://www.ncbi.nlm.nih.gov/nucest/%s?report=genbank",
    "pride": "http://www.ncbi.nlm.nih.gov/nucest/%s?report=genbank",
    "ddbj": "http://www.ncbi.nlm.nih.gov/nucest/%s?report=genbank",
    "bioproject": "http://www.ncbi.nlm.nih.gov/nucest/%s?report=genbank",
    "embl": "http://www.ncbi.nlm.nih.gov/nucest/%s?report=genbank",
    "sra": "http://www.ncbi.nlm.nih.gov/nucest/%s?report=genbank",
}

log = logging.getLogger("scholexplorer-portal")
log.setLevel(logging.INFO)
fh = logging.StreamHandler(sys.stdout) 
fh.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
log.addHandler(fh)
log.info("Scholexplorer Portal Restarted")


app.add_middleware(PrometheusMiddleware)
app.add_route("/metrics/", metrics)

@app.get('/')
def root():
    return FileResponse(os.path.join(os.path.join(_CURDIR, 'static' ),'index.html'))

@app.get("/favicon.ico")
def favicon():
    return FileResponse(os.path.join(os.path.join(_CURDIR, 'static' ),'favicon.ico'))

@app.get("/api/main_page_stats")
def main_page_stats():
    connector= DLIESConnector()
    return dict(result=connector.get_main_page_stats())

@app.post('/api/queryPid/')
def query_pid(*, pid:str= Form(...)):   
    print (pid) 
    connector = DLIESConnector()    
    return dict(result=connector.query_by_id(pid))



@app.post('/api/post/')
def query_post(*, start:int= Form(default=0), action:str=Form(default="query"), query:str=Form(...),filter:str=Form(default=None)):
    filter_key = None
    result = {}  
    if filter:
        filter_key = filter
    if action == 'query' and query is not None:
        connector = DLIESConnector()
        try:
            result = connector.simple_query(query, start=start, user_filter=filter_key)
        except Exception as e:
            log.error(e)
        return dict(result=result)
    else:
        return dict(error={'error_code': 'an error occur during query on server'})


@app.get('/api/item/{identifier}')
@app.post('/api/item/{identifier}')
def get_item(identifier:str, object_type:str=Form(default=None), start:int=Form(default=0)):
    if identifier:        
        connector = DLIESConnector()
        return dict(result=connector.item_by_id(identifier, object_type, start))
    else:
        return None