# -*- coding: utf-8 -*-
# @Time : 2022/5/24 21:30
# @Author : wangyinghao
# @Site : 
# @File : api_management_detail_view.py
# @Software: PyCharm
from django.views.generic import View
import json
from django.forms import model_to_dict
from automated_main.utils.http_format import response_success, response_failed
from automated_main.exception.my_exception import MyException
from automated_main.form.api_management import ApiManagementForm
from automated_main.models.api_automation.api_management import ApiManagement
from datetime import datetime


class ApiManagementView(View):

    def get(self, request, api_management_id, *args, **kwargs):
        """
        代表获取单个服务
        :param request:
        :param api_management_id:
        :param args:
        :param kwargs:
        :return:
        """

        try:
            api_management = ApiManagement.objects.get(id=api_management_id)
        except ApiManagement.DoesNotExist:
            return response_failed()
        else:
            return response_success(model_to_dict(api_management))

    def post(self, request, api_management_id, *args, **kwargs):
        """
        更新单个服务
        :param request:
        :param api_management_id:
        :param args:
        :param kwargs:
        :return:
        """
        body = request.body
        params = json.loads(body)
        form = ApiManagementForm(params)
        result = form.is_valid()
        if result:
            api_management_data = ApiManagement.objects.get(id=api_management_id)
            api_management_data.name = params['name']
            api_management_data.description = params['description']
            api_management_data.parent = params['parent']
            api_management_data.update_time = datetime.now()
            api_management_data.save()

        else:
            print(form.errors.as_json())
            raise MyException()

        return response_success()

    def delete(self, request, api_management_id, *args, **kwargs):

        ApiManagement.objects.filter(id=api_management_id).delete()
        ApiManagement.objects.filter(parent=api_management_id).delete()
        return response_success()
