# -*- coding: utf-8 -*-
# @Time : 2021/10/21 17:24
# @Author : wangyinghao
# @File : api_database_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
from automated_main.exception.my_exception import MyException
from automated_main.models.api_automation.api_database import APIDatabase
from automated_main.form.api_database import ApiDatabaseForm
from automated_main.utils.handle_db import HandleDB


class ApiDatabaseView(View):

    def get(self, request, api_database_id, *args, **kwargs):
        """
        代表获取单个API数据库
        :param request:
        :param api_database_id:数据库的id
        :param args:
        :param kwargs:
        :return:
        """
        api_database = APIDatabase.objects.filter(id=api_database_id).first()

        if api_database is None:
            return response_success()
        else:
            return response_success(model_to_dict(api_database))

    def post(self, request, api_database_id, *args, **kwargs):
        """
        代表更改API数据库
        :param request:
        :param api_database_id:
        :param args:
        :param kwargs:
        :return:
        """
        api_database = APIDatabase.objects.filter(id=api_database_id).first()
        if api_database is None:
            return response_success()
        body = request.body
        if not body:
            return response_success()
        data = json.loads(body)

        form = ApiDatabaseForm(data)

        if form.is_valid():
            APIDatabase.objects.filter(id=api_database_id).update(**form.cleaned_data)
            return response_success("编辑成功")
        else:
            raise MyException()

    def delete(self, request, api_database_id, *args, **kwargs):
        """
        代表删除单独API数据库
        :param request:
        :param api_database_id: API数据库ID
        :param args:
        :param kwargs:
        :return:
        """

        APIDatabase.objects.filter(id=api_database_id).delete()
        return response_success("删除成功")

    def put(self, request, *args, **kwargs):
        """
        代表创建API数据库
        :param request:
        :param args:
        :param kwargs:
        :return:
        """

        body = request.body
        if not body:
            return response_success()
        data = json.loads(body)

        form = ApiDatabaseForm(data)

        if form.is_valid():

            APIDatabase.objects.create(**form.cleaned_data)
            return response_success("创建成功")
        else:
            raise MyException(message="创建失败")


class DatabaseProcessingView(View):

    def post(self, request, *args, **kwargs):
        """
        连接数据库
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        body = request.body
        if not body:
            return response_success()
        data = json.loads(body)
        db = HandleDB(data['api_host'], int(data['api_port']), data['user'], data['password'], data['database'])
        sql = 'SELECT VERSION()'

        try:
            db.execution_results(sql)
            db.close()
            return response_success("调试成功")
        except Exception as e:
            print(e)
            pass
            return MyException(40000, message="调试失败")
