# (c) cavaliba.com  - data/api - testapi.py


import logging

from django.urls import reverse
from django.views.decorators.csrf import csrf_exempt

import app_data.api.helper as helper
from app_data.api.aaa import start_api
from app_data.tasks import submit_example_long
from app_home.log import DEBUG, log

logger = logging.getLogger(__name__)


#  ----------------------------------------------------------------------------
# /api/test/
#  ----------------------------------------------------------------------------
@csrf_exempt
def testapi(request):

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

    log(DEBUG, aaa=aaa_api, app="api", view="test", action="GET", status="OK", data="")
    logger.debug("Ceci est un message d'api test : debug")
    logger.info("Ceci est un message d'api test : info")
    logger.warn("Ceci est un message d'api test : warn")
    logger.error("Ceci est un message d'api test : error")
    logger.critical("Ceci est un message d'api test : critical")

    return helper.send_ok()

    # call long async DataTask - v3.33
    params = {"steps": 30, "duration": 2}

    handle = submit_example_long(params=params, owner_type="api", owner_id="testapi")

    if handle:
        task_url = request.build_absolute_uri(reverse("api:api_task_detail", args=[handle]))
        reply = {"test": "RUNNING", "handle": handle, "task_url": task_url}
        return helper.send_response(request, reply, 200)

    else:
        return helper.send_error("failed - this task already exists", 405)

    # time.sleep(5)
    # return helper.send_response(request, reply, 200)
    # content = json.dumps(reply, indent=2, ensure_ascii=False).encode('utf8')
    # content_type = 'application/json; charset=utf-8'
    # return HttpResponse(content + b"\n", status=200, content_type=content_type)
