from rest_framework import status
from rest_framework.response import Response
from rest_framework.decorators import api_view
from .utils import compose_protobuf_message
from device_data_op.models import (TableDevCmdNamePoll,
                                   TableAllDevCmdDefine,
                                   TableXproAllDevinfo)
from device_data_op.serializers import (TableDevCmdNamePollSerializer,
                                        TableAllDevCmdDefineSerializer)

from mqtt.mqtt import client as mqtt_client


@api_view(['GET'])
def cmd_list(request, protocol_name: str):
    """
    返回传入协议的所有发出指令名
    """
    cmd_lists = TableDevCmdNamePoll.objects.filter(protocol_name=protocol_name).all()
    serializer = TableDevCmdNamePollSerializer(cmd_lists, many=True)
    
    ret_data = [data['cmd_name'] for data in serializer.data
                if data['cmd_type'] == 'TX']
    return Response(data=ret_data, status=status.HTTP_200_OK)
    

@api_view(['GET'])
def cmd_fields_list(request, cmd_name: str):
    """
    返回传入指令所需要的字段
    """
    cmd_fields = TableAllDevCmdDefine.objects.filter(cmd_name=cmd_name).all()
    serializer = TableAllDevCmdDefineSerializer(cmd_fields, many=True)

    ret_data = [data['fieldname'] for data in serializer.data]
    return Response(data=ret_data, status=status.HTTP_200_OK)


@api_view(['POST'])
def publish_message(request):
    """
    发送指令到 device

    :param request:
    {
        "type": "device",
        "station_id": "XX1",
        "device_id": 1,
        "cmd_name": "HY_ACU7M5_PositionSet",
        "fields": [
            {
                "fieldname": "Xaxis",
                "value": "120"
            },
            {
                "fieldname": "Yaxis",
                "value": "60"
            }
        ]
    }
    """

    if request.data['station_id'] == "XX1":
        topic = "/1/1/1/3"
        dst_suid = 0x1113_0000
    elif request.data['station_id'] == "XX0":
        topic = "/1/1/0/3"
        dst_suid = 0x1103_0000
    else:
        return Response(status=status.HTTP_400_BAD_REQUEST)

    message = compose_protobuf_message(request.data, dst_suid)

    rc, mid = mqtt_client.publish(topic, message)
    return Response(status=status.HTTP_200_OK)
