
from flask import Flask, request, jsonify
from werkzeug.serving import make_server
from werkzeug.exceptions import HTTPException

app = Flask(__name__)
context = {}

@app.errorhandler(HTTPException)
def handle_http_exception(e):
    return e

@app.errorhandler(Exception)
def handle_exception(e):
    if 'process_manager' in context:
        process_manager = context['process_manager']
        process_manager.logger.exception('Error on request {}'.format(str(request)))

    return 500, str(e)

@app.route('/', methods=['GET'])
def get_session():
    process_manager = context['process_manager']
    return jsonify(process_manager.session.__dict__)

@app.route('/check', methods=['GET'])
def check():
    return True

@app.route('/processes', methods=['GET'])
def list_processes():
    process_manager = context['process_manager']

    descs = [p.desc for p in process_manager.processes]

    return jsonify(descs)

@app.route('/new', methods=['POST', 'GET'])
def new_process():
    process_manager = context['process_manager']
    args = request.data
    if not args:
        args = {
            'command': request.args.get('command').split(),
            'name': request.args.get('name'),
            'start': request.args.get('start') is None or request.args.get('start').lower() == 'true',
            'mandatory': request.args.get('mandatory') is not None and request.args.get('mandatory').lower() == 'true'
        }

    p = process_manager.new_process(**args)
    return jsonify(p.desc)


@app.route('/cleanup', methods=['POST', 'GET'])
def cleanup():
    process_manager = context['process_manager']
    process_manager.cleanup()
    return 'OK'


@app.route('/poll', methods=['GET'])
def poll():
    process_manager = context['process_manager']
    name = request.args.get('name')
    return jsonify(process_manager.poll(name=name))


@app.route('/list', methods=['GET'])
def list():
    process_manager = context['process_manager']
    return jsonify(process_manager.list())


@app.route('/signal', methods=['POST', 'GET'])
def send_signal():
    process_manager = context['process_manager']
    name = request.args.get('name')
    signal = request.args.get('signal')
    process_manager.send_signal(name=name, signal=signal)
    return 'OK'


@app.route('/kill', methods=['POST', 'GET'])
def kill():
    process_manager = context['process_manager']
    name = request.args.get('name')
    process_manager.kill(name=name)
    return 'OK'


def start_process_server(process_manager, host=None, port=None):
    context['process_manager'] = process_manager

    #app.logger = pm.logger
    app.logger.disabled = True

    # prepare flask server
    server = make_server(host=host, port=port, app=app)
    context['server'] = server

    # ... and start it
    server.serve_forever()

def stop_process_server():
    if 'server' in context:
        server = context['server']
        server.shutdown()
        #del context['server']

#
# Services Manager
#
@app.route('/services/tsem', methods=['POST', 'GET'])
def tsem_check():
    service_manager = context['process_manager']
    print("/services/tsem")
    response = service_manager.tsem_check()
    return jsonify(response)


@app.route('/services/start', methods=['POST', 'GET'])
def start_services():
    service_manager = context['process_manager']
    service_names = request.args.getlist(key="name")
    print("/services/start: {0}".format(service_names))
    response = service_manager.start_services(services_names=service_names)
    return jsonify(response)


@app.route('/services/stop', methods=['POST', 'GET'])
def stop_services():
    service_manager = context['process_manager']
    service_names = request.args.getlist(key="name")
    print("/services/stop: {0}".format(service_names))
    response = service_manager.stop_services(services_names=service_names)
    return jsonify(response)


@app.route('/services/restart', methods=['POST', 'GET'])
def restart_services():
    service_manager = context['process_manager']
    service_names = request.args.getlist(key="name")
    print("/services/restart: {0}".format(service_names))
    response = service_manager.restart_services(services_names=service_names)
    return jsonify(response)


@app.route('/services/status', methods=['POST', 'GET'])
def status_services():
    service_manager = context['process_manager']
    service_names = request.args.getlist(key="name")
    print("/services/status: {0}".format(service_names))
    response = service_manager.status_services(services_names=service_names)
    return jsonify(response)


@app.route('/services/processes', methods=['POST', 'GET'])
def get_torii_processes():
    service_manager = context['process_manager']
    service_names = request.args.getlist(key="name")
    print("/services/processes: {0}".format(service_names))
    response = service_manager.get_torii_processes(services_names=service_names)
    return jsonify(response)
