from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.utils.translation import gettext as _


import json


@login_required
def k356_validate(request):

    us = request.user.setting
    if request.method == "POST":
        try:
            fingerprint = json.loads(request.body)["fingerprint"]

        except Exception as e:
            return JsonResponse(
                {
                    "ok": False,
                    "error": str(e),
                }
            )

        if us.k356_key_fingerprint:
            if us.k356_key_fingerprint != fingerprint:
                return JsonResponse(
                    {
                        "ok": False,
                        "error": _("Unable to verify key."),
                    }
                )

        else:
            us.k356_key = True
            us.k356_key_fingerprint = fingerprint
            us.save()

        return JsonResponse(
            {
                "ok": True,
            }
        )

    return JsonResponse(
        {
            "key": us.k356_key,
            "fingerprint": us.k356_key_fingerprint,
        }
    )


@login_required
def keys(request):

    us = request.user.setting

    if request.method == "POST":
        try:
            data = json.loads(request.body)

        except Exception:
            return JsonResponse({"error": "INVALID_DATA"}, status=401)

        if us.private_key and not request.GET("force", "false") == "true":
            return JsonResponse({"error": "KEY_EXISTS"}, status=401)

        us.private_key = data.get("privateKey", None)
        us.public_key = data.get("publicKey", None)
        us.save()

    return JsonResponse(
        {
            "privateKey": us.private_key,
            "publicKey": us.public_key,
        }
    )
