import json
import logging
from uuid import UUID

from django.utils.translation import gettext_lazy
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.views import APIView

from inputs.services.remove_loginputs import remove_all_log_inputs
from license_info.tools import get_activation_token, activate_license, activate_license_auto, get_license_info

_log = logging.getLogger()


class LicenseTokenAPIView(APIView):
    """API View for getting token by serial number"""

    permission_classes = [AllowAny]

    def get(self, request, serial: UUID, *args, **kwargs) -> Response:
        data = {"token": get_activation_token(serial)}
        return Response(data)


class LicenseActivateManualAPIView(APIView):
    """APi View for manual license"""

    permission_classes = [AllowAny]

    def post(self, request, *args, **kwargs) -> Response:
        self.activate()
        # return HttpResponseRedirect(reverse_lazy("index"))  todo maybe redirect?
        return Response({'license': 'activated'})

    def activate(self):
        file = self.request.FILES['file']
        result = file.read().decode('utf-8')
        data = json.loads(result)
        activate_license(data)
        remove_all_log_inputs()


class LicenseActivateAutoAPIView(APIView):
    """API View for auto activation license by serial number"""
    permission_classes = [AllowAny]

    def get(self, request, serial: UUID, *args, **kwargs) -> Response:
        activate_license_auto(serial)
        remove_all_log_inputs()
        # return HttpResponseRedirect(reverse_lazy("index"))  todo maybe redirect?
        return Response({'license': 'activated'})


# This map hold name and description for all options and features
# For now, we believe that option and feature names are different
LICENSE_DATA_MAP = {
    "event_processing": {"name": gettext_lazy("Event processing"),
                         "description": gettext_lazy("Enable correlator and event processing")},
    "event_sources": {"name": gettext_lazy("Event sources"),
                      "description": gettext_lazy("Event sources count")},
    "incident_processing": {"name": gettext_lazy("Incident processing"),
                            "description": gettext_lazy("Enable incident processing")}
}


class LicenseInfoAPIView(APIView):
    """API View fot getting License information."""

    def get(self, request, *args, **kwargs) -> Response:
        try:
            license_data = get_license_info()
        except RuntimeError as e:
            _log.error(f"Got error from license client: {e}")
            return Response({}, status=400)

        features = []
        options = []

        if license_data is not None:
            for cur in license_data["features"]:
                if cur in LICENSE_DATA_MAP:
                    features.append(LICENSE_DATA_MAP[cur])

            for key, value in license_data["options"].items():
                data = LICENSE_DATA_MAP[key]
                data["value"] = value
                options.append(data)

        data = {'license': license_data, 'features': features, 'options': options}

        return Response(data)
