from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from device_data_op.models import TableXproAllDevinfo
from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi
from .device_manager import SIMULATE_DEVICE_PROCESS, start_signal, stop_signal


@swagger_auto_schema(method='post', request_body=openapi.Schema(
    type=openapi.TYPE_OBJECT,
    properties={
        'status': openapi.Schema(type=openapi.TYPE_BOOLEAN),
        'protocol_name': openapi.Schema(type=openapi.TYPE_STRING),
        'device_name': openapi.Schema(type=openapi.TYPE_STRING)
    }
), responses={200: 'OK', 400: 'Bad Request', 500: 'Internal Server Error'})
@api_view(['POST'])
def change_simulate_device_status(request):
    """
    通过 subprocess 模块来启动或者关闭模拟设备
    """
    device_status = request.data.get('status')
    protocol_name = request.data.get('protocol_name')
    device_name = request.data.get('device_name')
    if device_status is None or protocol_name is None or device_name is None:
        return Response(status=status.HTTP_400_BAD_REQUEST)

    # 获取改设备的端口
    device_communication = TableXproAllDevinfo.objects.filter(dev_name=device_name).first()
    if "TCP" in device_communication.comunitate_mode.upper():
        device_port = device_communication.tcp_port
    else:
        return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    # 发送相关信号
    if device_status == 'true':
        if device_name in SIMULATE_DEVICE_PROCESS.keys():
            return Response(status=status.HTTP_400_BAD_REQUEST)
        start_signal.send(sender=None, protocol_name=protocol_name, device_name=device_name, port=device_port)
    else:
        if device_name not in SIMULATE_DEVICE_PROCESS.keys():
            return Response(status=status.HTTP_400_BAD_REQUEST)
        stop_signal.send(sender=None, device_name=device_name)
    
    return Response(status=status.HTTP_200_OK)

