#!/usr/bin/python

from flask import Flask, jsonify, request
from flask.json import JSONEncoder
from eu.dnetlib.es_connector import DLIESConnector
from flask_prometheus import monitor

from logger import dlilogger

DLI_INDEX = None
ES_HOST = None


def read_properies():
    f = open('api.properties')
    for line in f:
        s = line.strip().split('=')
        if s[0] == 'api.index':
            DLI_INDEX = s[1]
        if s[1] == 'es_index':
            ES_HOST = [x.strip() for x in s[1].split(',')]


class MyJSONEncoder(JSONEncoder):
    def default(self, obj):
        return obj.__dict__


app = Flask(__name__)
app.debug = False
app.json_encoder = MyJSONEncoder

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",
}


class InvalidUsage(Exception):
    status_code = 400

    def __init__(self, message, status_code=None, payload=None):
        Exception.__init__(self)
        self.message = message
        if status_code is not None:
            self.status_code = status_code
        self.payload = payload

    def to_dict(self):
        rv = dict(self.payload or ())
        rv['message'] = self.message
        return rv


# Routes
@app.route('/')
def root():
    return app.send_static_file('index.html')


@app.route('/<path:path>')
def static_proxy(path):
    # send_static_file will guess the correct MIME type
    return app.send_static_file(path)


@app.route('/api/item/<path:identifier>', methods=['post', 'get'])
def get_item(identifier):
    if identifier:
        object_type = request.form.get('type')
        start = request.form.get('from')
        if object_type and len(object_type) == 0:
            object_type = None
        if start and len(start) == 0:
            start = None
        elif start:
            start = int(start)
        connector = DLIESConnector()
        return jsonify(result=connector.item_by_id(identifier, object_type, start))
    else:
        raise InvalidUsage('This view is gone', status_code=410)


@app.route('/api/stats/', methods=['post', 'get'])
def stats():
    raise Exception("Method to be implemented")
    # q = QueryResolver(host, base_dnet_url)
    # return jsonify(stats=q.get_stats())


@app.route('/api/ds_info/', methods=['post', 'get'])
def info():
    raise Exception("Method to be implemented")


@app.route('/api/stats_detail/', methods=['post', 'get'])
def stats_detail():
    return ""


@app.route('/api/resolveId', methods=['get'])
def resolveIdentifier():
    pid = request.form.get('pid')
    pid_type = request.form.get('pid_type')
    if pid_type!= None:
        if pid_type.lower() in  pid_resolver:
            return pid_resolver[pid_type.lower()] % pid
        elif pid_type.lower().strip() == 'url':
            return pid
        else:
            return "http://identifiers.org/%s:%s" % (pid_type, pid)
    return ""



@app.route('/api/queryPid/', methods=['post'])
def query_pid():
    if 'pid' in request.form:
        print "pid Request for %s "%request.form['pid']
    connector = DLIESConnector()
    result = connector.query_by_id(request.form['pid'])
    return jsonify(result=result)


@app.route('/api/post/', methods=['post', 'get'])
def query_post():
    action = None
    query = None
    filter_key = None
    result = {}

    start = 0
    if 'action' in request.form:
        action = request.form['action']
    if 'query' in request.form:
        query = request.form['query']
    if 'start' in request.form:
        start = 0
        try:
            start = int(request.form.get('start',0))
        except:
            pass
    if 'filter' in request.form:
        filter_key = request.form['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:
            print e
        return jsonify(result=result)
    else:
        return jsonify(error={'error_code': 'an error occur during query on server'})


if __name__ == '__main__':

    app.logger.addHandler(dlilogger)
    monitor(app, port=8000)
    app.run()
    # app.run(host="0.0.0.0")
