#!/usr/bin/env python

import uta
from flask import Flask, jsonify, abort
from flask.ext import restful
from flask.ext.restful import reqparse, Api, Resource
from uta.db.transcriptdb import TranscriptDB
from uta.tools.hgvsmapper import HGVSMapper

"""
Example usage and output:

curl http://127.0.0.1:5000/uta/api -d "hgvsg=NC_000007.13:g.36561662C>T&ac=NM_001177507.1&ref=GRCh37.p10"
{
  "hgvsc": "NM_001177507.1:c.1486C>T",
  "hgvsp": "TBD",
  "uta_version": "version is not working..."
}
"""

"""
This example from the documentation shows that the status code is returned - this does not seem to be working. Instead
it only shows the message.
via: http://flask-restful.readthedocs.org/en/latest/quickstart.html
$ curl -d 'rate=foo' http://127.0.0.1:5000/
{'status': 400, 'message': 'foo cannot be converted to int'}
"""

app = Flask(__name__)
api = restful.Api(app)

parser = reqparse.RequestParser()
hgvsmapper = HGVSMapper(db=TranscriptDB(), cache_transcripts=True)

# RESTful interface using POST
# POST is necessary to properly encode the transcript names
class HGVSMapper(restful.Resource):
    def post(self):
        parser.add_argument('hgvsg', type=str, help='Missing HGVS location e.g. hgvsg=NC_000007.13:g.36561662C>T', required=True)
        parser.add_argument('ac', type=str, help='Missing accession e.g. ac=NM_001177507.1', required=True)
        parser.add_argument('ref', type=str, help='Missing genomic build reference e.g. ref=GRCh37.p10', required=True)
        args = parser.parse_args()

        try:
            hgvsc = hgvsmapper.hgvsg_to_hgvsc(args['hgvsg'], ac=args['ac'], ref=args['ref'])
        except Exception as error:
            return jsonify({'message': 'Bad Request to HGVSMapper. {0}'.format(error)})

        uta_version = uta.__version__
        if uta_version is None:
            uta_version = 'version is not working...'

        return jsonify({'uta_version': uta_version,
                        'hgvsc': hgvsc,
                        'hgvsp': 'TBD'})


api.add_resource(HGVSMapper, '/uta/api')


if __name__ == '__main__':
    app.run(debug=True)


## <LICENSE>
## Copyright 2014 UTA Contributors (https://bitbucket.org/invitae/uta)
## 
## Licensed under the Apache License, Version 2.0 (the "License");
## you may not use this file except in compliance with the License.
## You may obtain a copy of the License at
## 
##     http://www.apache.org/licenses/LICENSE-2.0
## 
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.
## </LICENSE>
