from rest_framework import serializers as serializer

from common.forms.models import Form, FormAttribute
from common.utils.models import BaseConnection


class FormCreateSerializer(serializer.Serializer):
    table = serializer.CharField(required=True,
                                 allow_blank=False,
                                 allow_null=False)
    name = serializer.CharField(required=True,
                                allow_blank=False,
                                allow_null=False)

    form_attribute = serializer.ListField(child=serializer.DictField(),
                                          required=True,
                                          allow_empty=False,
                                          allow_null=False,
                                          write_only=True)

    def create(self, validated_data):
        db_connect = BaseConnection()
        sql = "create table {} ( id INT NOT NULL AUTO_INCREMENT,".format(
            validated_data.get("table"))
        for item in validated_data.get("form_attribute"):
            sql += "{} {},".format(item.get("attribute"),
                                   item.get("data_type"))
        sql += "PRIMARY KEY (id))"
        db_connect.query(sql)
        form = Form.objects.create(table=validated_data.get("table"),
                                   name=validated_data.get("name"))
        form_attributes = []
        for item in validated_data.get("form_attribute"):
            form_attributes.append(
                FormAttribute(attribute=item.get("attribute"),
                              data_type=item.get("data_type"),
                              explain=item.get("explain"),
                              form=form))
        FormAttribute.objects.bulk_create(form_attributes)

        return form
