from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from sandbox.apps.devices.core.consts import EmulatorTypesInt
from .serializers import FirmwareEmulatorSerializer
from sandbox.apps.firmware.core.publisher import publish_new_device_emulator_fw, publish_new_gateway_emulator_fw


class FirmwareEmulatorAPIView(APIView):

    def post(self, request):
        """
        Sign and publish new firmware for device emulator
        """
        serializer = FirmwareEmulatorSerializer(data=request.data)
        if not serializer.is_valid():
            return Response(status=status.HTTP_400_BAD_REQUEST, data=serializer.errors)

        device_type = int(request.data.get('device_type'))
        if device_type == EmulatorTypesInt.GATEWAY:
            publish_new_gateway_emulator_fw()
        elif device_type == EmulatorTypesInt.IOT_DEVICE:
            publish_new_device_emulator_fw()
        return Response(status=status.HTTP_200_OK)
