from flask import Flask, request,render_template, send_from_directory
from healthcareio.params import SYS_ARGS
import healthcareio.analytics
import os
import json
app = Flask(__name__)
@app.route("/favicon.ico")
def _icon():
    return send_from_directory(os.path.join([app.root_path, 'static','img','logo.svg']),
                               'favicon.ico', mimetype='image/vnd.microsoft.icon')
@app.route("/")
def init():
    e = SYS_ARGS['engine']
    sections = {"remits":e.info['835'],"claims":e.info['837']}
    _args = {"sections":sections}
    return render_template("index.html",**_args)
@app.route("/format/<id>/<index>",methods=['POST'])
def _format(id,index):
    
    e = SYS_ARGS['engine']
    key = '837' if id == 'claims' else '835'
    index = int(index)
    # p = e.info[key][index]
    p = e.apply(type=id,index=index)
    
    #
    r = []
    for item in p[0]['pipeline'] :
        _item= dict(item)
        del _item['sql']
        del _item ['data']
        
        _item = dict(_item,**healthcareio.analytics.Apex.apply(item))
        if 'apex' in _item or 'html' in _item:
            r.append(_item)
        
    r = {"id":p[0]['id'],"pipeline":r}
    return json.dumps(r),200
@app.route("/get/<id>/<index>",methods=['GET'])
def get(id,index):
    e = SYS_ARGS['engine']
    key = '837' if id == 'claims' else '835'
    index = int(index)
    # p = e.info[key][index]
    p = e.apply(type=id,index=index)
    r = {}
    for item in p[0]['pipeline'] :
        
        _item= [dict(item)]
        
        r[item['label']] = item['data'].to_dict(orient='record')
        # del _item['sql']
        # del _item ['data']
    #     print (item['label'])
    #     _item['apex'] = healthcareio.analytics.Apex.apply(item)
    #     if _item['apex']:
    #         r.append(_item)
        
    # r = {"id":p[0]['id'],"pipeline":r}
    return json.dumps(r),200
@app.route("/reload",methods=['POST'])
def reload():
    # e = SYS_ARGS['engine']
    # e.apply()
    PATH= SYS_ARGS['config'] if 'config' in SYS_ARGS else os.sep.join([os.environ['HOME'],'.healthcareio','config.json'])    
    e = healthcareio.analytics.engine(PATH)
    # e.apply()
    SYS_ARGS['engine'] = e

    return "1",200
if __name__ == '__main__' :
    PORT = int(SYS_ARGS['port']) if 'port' in SYS_ARGS else 5500
    DEBUG= int(SYS_ARGS['debug']) if 'debug' in SYS_ARGS else 0
    SYS_ARGS['context'] = SYS_ARGS['context'] if 'context' in SYS_ARGS else ''
    #
    # 
    PATH= SYS_ARGS['config'] if 'config' in SYS_ARGS else os.sep.join([os.environ['HOME'],'.healthcareio','config.json'])
    
    e = healthcareio.analytics.engine(PATH)
    # e.apply(type='claims',serialize=True)
    SYS_ARGS['engine'] = e
    app.run(host='0.0.0.0',port=PORT,debug=DEBUG,threaded=True)