from datetime import datetime

rels = dict(issupplementto="IsSupplementTo", issupplementedby="IsSupplementedBy", references="References",
            isreferencedby="IsReferencedBy")

pid_resolver = {
    "pdb": "http://www.rcsb.org/pdb/explore/explore.do?structureId=%s",
    "ncbi-n": "http://www.ncbi.nlm.nih.gov/gquery/?term=%s",
    "ncbi": "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",
}


def resolveIdentifier(pid, pid_type):
    if pid_type != None:
        if pid_type.lower() in pid_resolver:
            return pid_resolver[pid_type.lower()] % pid
        else:
            return "http://identifiers.org/%s:%s" % (pid_type, pid)


def get_scholix_resource(item):
    title = ''
    if 'title' in item:
        title = item.title
    if len(title):
        if title[0] == '"' and title[-1] == '"':
            title = title[1:-1]
    identifier = [dict(ID=x.identifier, IDScheme=x.schema, IDURL=resolveIdentifier(x.identifier, x.schema)) for x in
                  item.identifier]
    identifier.append(dict(ID=item.dnetIdentifier, IDScheme='D-Net Identifier', IDURL='http://scholexplorer.openaire.eu/index.html#/detail/%s'%item.dnetIdentifier))
    creator = []
    if 'creator' in item:
        creator = [dict(Name=x.name) for x in item.creator]
    publicationDate = None
    if 'publicationDate' in item:
        publicationDate = item.publicationDate
    publisher = []
    if 'publisher' in item:
        publisher = [dict(name= x.name) for x in item.publisher]
    c_type = item.objectType
    if item.objectType == 'publication':
        c_type = 'literature'

    resource = dict(Title=title, Identifier=identifier, Creator=creator, PublicationDate= publicationDate, Publisher = publisher, Type= c_type)

    return resource


def create_response(response, current_page):
    result = {'totalLinks': response.hits.total, 'currentPage': current_page,
              'totalPages': 1 + response.hits.total / 100, 'result': []}
    now = datetime.now()
    for item in response.hits:
        current_item = {'LinkPublicationDate': now.strftime("%Y-%m-%d"), 'HarvestedDate': now.strftime("%Y-%m-%d"),
                        "LinkProvider": []}
        for linkProvider in item.linkprovider:
            current_item['LinkProvider'].append(dict(name=linkProvider.name,
                                                     identifier=[dict(ID=x.identifier, IDScheme=x.schema) for x in
                                                                 linkProvider.identifiers]))

        rel_sub_type = rels.get(item.relationship.name.lower(), "IsRelatedTo")
        current_item['RelationshipType'] = dict(Name=rel_sub_type, SubType=item.relationship.name,
                                                SubTypeSchema=item.relationship.schema)

        current_item['source'] = get_scholix_resource(item.source)
        current_item['target'] = get_scholix_resource(item.target)

        result['result'].append(current_item)

    return result
