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

import json

from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt

from app_home.log import log, DEBUG

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

from django.urls import reverse

from app_data.tasks import submit_example_long


#  ----------------------------------------------------------------------------
# /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="")


    # 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)
