from django.test import TestCase

from ichec_django_core.serializers.form import FormSerializer, PopulatedFormSerializer


class TestFormSerializer(TestCase):

    def test_deserialize_form(self):

        data = {
            "groups": [
                {
                    "label": "test",
                    "description": "description",
                    "order": 1,
                    "fields": [
                        {
                            "label": "field_label",
                            "key": "field_key",
                            "required": False,
                            "order": 0,
                            "field_type": "BOOLEAN",
                            "description": "Description",
                            "default": "false",
                        }
                    ],
                }
            ]
        }
        serializer = FormSerializer(data=data)
        self.assertTrue(serializer.is_valid())

        instance = serializer.create(serializer.validated_data)
        self.assertEqual(instance.groups.all()[0].fields.all()[0].key, "field_key")

        serialized = FormSerializer(instance).data
        serialized["groups"][0]["fields"][0]["default"] = "true"

        update_serializer = FormSerializer(data=serialized)
        self.assertTrue(update_serializer.is_valid())
        instance = update_serializer.update(instance, update_serializer.validated_data)
        self.assertEqual(instance.groups.all()[0].fields.all()[0].default, "true")

        data = {"values": [{"value": "test", "field": "1"}]}
        serializer = PopulatedFormSerializer(data=data)
        self.assertTrue(serializer.is_valid())

        instance = serializer.create(serializer.validated_data)
        self.assertEqual(instance.values.all()[0].field.id, 1)

        serialized = PopulatedFormSerializer(instance).data
        serialized["values"][0]["value"] = "updated"
        serialized["values"][0]["field"] = 1

        update_serializer = PopulatedFormSerializer(data=serialized)
        self.assertTrue(update_serializer.is_valid(raise_exception=True))
        instance = update_serializer.update(instance, update_serializer.validated_data)
        self.assertEqual(instance.values.all()[0].value, "updated")
