# (c) cavaliba.com  - status - api.py

import json
import pprint

from django.views.decorators.csrf import csrf_exempt

from app_user.aaa_api import start_api
import app_data.api.helper as helper

from app_status.common import get_monitors
from app_status.common import get_monitor_names
from app_status.models import StatusRaw




# response
# {'results': [
#         {
#          'keyname': 'apache',
#          'duration': 23276108,
#          'http_code': 200,
#          'name': 'www.apache.org',
#          'status': True,
#          'error': 'reject pattern found',
#         },
#         {
#          'keyname': '....',
#         ...
#         },
# ]}

def store_response(results):
    '''
    Store response (monitor checks) in Status DB

    Args:
        results: array of monitor check responses

    Output:
        error : None or string with error message
    '''

    
    if not isinstance(results, list):
        return "bad response"

    monitor_names = get_monitor_names()

    for check in results:

        #pprint.pprint(check)

        monitor = check.get('keyname', None)
        if monitor not in monitor_names:
            return f"invalid monitor {monitor}"

        obj = StatusRaw()
        obj.monitor = monitor
        if check['status']:
            obj.status = True
        else:
            obj.status = False
        if check['error']:
            obj.data = check.get('error', '')

        obj.usec = int(check.get('duration', 0) / 1000)
        obj.save()

    return

#   ----------------------------------------------------------------------------
# GET worklist/ ; POST worklist/
#   ----------------------------------------------------------------------------
@csrf_exempt
def worklist(request):

    aaa_api = start_api(request, permission="p_status_poller")
    if not aaa_api["is_allowed"]:
        return helper.send_denied()

    # send worklist (list of monitors to check)
    if request.method == "GET":

        mlist = get_monitors()
        monitors = []

        for m in mlist:
            item = {}
            item["keyname"] = m.keyname
            item["displayname"] = m.displayname
            item["type"] = m.type
            item["is_enabled"] = m.is_enabled
            item["timeout"] = m.timeout              # msec
            item["target"] = m.target
            
            if m.type == "HTTP":
                item["http_code"] = m.http_code
                item["http_ssl_verify"] = m.http_ssl_verify
                item["http_allow_redirect"] = m.http_allow_redirect
                item["http_pattern"] = m.pattern

            monitors.append(item)

        # TODO: worklist version
        reply = {
            "version": "1234567890",
            "monitors": monitors
        }
        return helper.send_response(request, reply, 200)

    # POST : submited response
    else:
        try:
            datalist = json.loads(request.body.decode("utf-8"))
        except Exception as e:
            helper.send_error(e, 400)

        reply = {'status': 'OK'}
        if isinstance(datalist, dict) and 'results' in datalist:
            err = store_response(datalist['results'])
            if err:
                reply = {'status': 'KO', 'error': err}
        else:
            reply = {'status': 'KO', 'error': 'bad json response'}

        return helper.send_response(request, reply, 200)
