from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from .models import (TableAllDevCmdDefine, TableDevCmdNamePoll, 
                     TableSoftLimitAngle, TableXproAllDevinfo)
from .serializers import (TableAllDevCmdDefineSerializer, TableDevCmdNamePollSerializer, 
                          TableSoftLimitAngleSerializer, TableXproAllDevinfoSerializer)
from .utils import tree_data


class TableAllDevCmdDefineView(ModelViewSet):
    queryset = TableAllDevCmdDefine.objects.all()
    serializer_class = TableAllDevCmdDefineSerializer

    def list(self, request):
        serializer = self.get_serializer(self.get_queryset(), many=True)
        data = tree_data(serializer.data, 'cmd_name')
        return Response(data)
    
    def perform_destroy(self, instance):
        """
        删除某个字段，需要将字段的 index 更新
        """
        
        # 获取改字段的 cmd_name
        cmd_name = instance.cmd_name
        super().perform_destroy(instance)
        fields = self.get_queryset().filter(cmd_name=cmd_name).all()

        # 更新字段的 index
        for i in range(len(fields)):
            print(fields[i])
            fields[i].fieldindex = i + 1
            fields[i].save()


class TableDevCmdNamePollView(ModelViewSet):
    queryset = TableDevCmdNamePoll.objects.all()
    serializer_class = TableDevCmdNamePollSerializer

    def list(self, request):
        serializer = self.get_serializer(self.get_queryset(), many=True)
        data = tree_data(serializer.data, 'protocol_name')
        return Response(data)
    

class TableSoftLimitAngleView(ModelViewSet):
    queryset = TableSoftLimitAngle.objects.all()
    serializer_class = TableSoftLimitAngleSerializer


class TableXproAllDevinfoView(ModelViewSet):
    queryset = TableXproAllDevinfo.objects.all()
    serializer_class = TableXproAllDevinfoSerializer




