from __future__ import annotations

import json
import re

import pytest
from django import forms
from django.core import exceptions, serializers
from django.core.management import call_command
from django.db import connection, models
from django.db.migrations.writer import MigrationWriter
from django.db.models import Q, Value
from django.test import SimpleTestCase, TestCase, TransactionTestCase, override_settings
from django.test.utils import isolate_apps

from django_mysql.forms import SimpleSetField
from django_mysql.models import SetCharField, SetF
from django_mysql.test.utils import override_mysql_variables
from tests.testapp.models import CharSetDefaultModel, CharSetModel, IntSetModel


class TestSaveLoad(TestCase):
    def test_char_easy(self):
        s = CharSetModel.objects.create(field={"big", "comfy"})
        assert s.field == {"comfy", "big"}
        s = CharSetModel.objects.get(id=s.id)
        assert s.field == {"comfy", "big"}

        s.field.add("round")
        s.save()
        assert s.field == {"comfy", "big", "round"}
        s = CharSetModel.objects.get(id=s.id)
        assert s.field == {"comfy", "big", "round"}

    def test_char_string_direct(self):
        s = CharSetModel.objects.create(field="big,bad")
        s = CharSetModel.objects.get(id=s.id)
        assert s.field == {"big", "bad"}

    def test_is_a_set_immediately(self):
        s = CharSetModel()
        assert s.field == set()
        s.field.add("bold")
        s.field.add("brave")
        s.save()
        assert s.field == {"bold", "brave"}
        s = CharSetModel.objects.get(id=s.id)
        assert s.field == {"bold", "brave"}

    def test_empty(self):
        s = CharSetModel.objects.create()
        assert s.field == set()
        s = CharSetModel.objects.get(id=s.id)
        assert s.field == set()

    def test_char_cant_create_sets_with_empty_string(self):
        with pytest.raises(ValueError):
            CharSetModel.objects.create(field={""})

    def test_char_cant_create_sets_with_commas(self):
        with pytest.raises(ValueError):
            CharSetModel.objects.create(field={"co,mma", "contained"})

    def test_char_basic_lookup(self):
        mymodel = CharSetModel.objects.create()
        empty = CharSetModel.objects.filter(field="")

        assert empty.count() == 1
        assert empty[0] == mymodel

        mymodel.delete()

        assert empty.count() == 0

    def test_char_lookup_contains(self):
        self.check_char_lookup("contains")

    def test_char_lookup_icontains(self):
        self.check_char_lookup("icontains")

    def check_char_lookup(self, lookup):
        lname = "field__" + lookup
        mymodel = CharSetModel.objects.create(field={"mouldy", "rotten"})

        mouldy = CharSetModel.objects.filter(**{lname: "mouldy"})
        assert mouldy.count() == 1
        assert mouldy[0] == mymodel

        rotten = CharSetModel.objects.filter(**{lname: "rotten"})
        assert rotten.count() == 1
        assert rotten[0] == mymodel

        clean = CharSetModel.objects.filter(**{lname: "clean"})
        assert clean.count() == 0

        with pytest.raises(ValueError):
            list(CharSetModel.objects.filter(**{lname: {"a", "b"}}))

        both = CharSetModel.objects.filter(
            Q(**{lname: "mouldy"}) & Q(**{lname: "rotten"})
        )
        assert both.count() == 1
        assert both[0] == mymodel

        either = CharSetModel.objects.filter(
            Q(**{lname: "mouldy"}) | Q(**{lname: "clean"})
        )
        assert either.count() == 1

        not_clean = CharSetModel.objects.exclude(**{lname: "clean"})
        assert not_clean.count() == 1

        not_mouldy = CharSetModel.objects.exclude(**{lname: "mouldy"})
        assert not_mouldy.count() == 0

    def test_char_len_lookup_empty(self):
        mymodel = CharSetModel.objects.create(field=set())

        empty = CharSetModel.objects.filter(field__len=0)
        assert empty.count() == 1
        assert empty[0] == mymodel

        one = CharSetModel.objects.filter(field__len=1)
        assert one.count() == 0

        one_or_more = CharSetModel.objects.filter(field__len__gte=0)
        assert one_or_more.count() == 1

    def test_char_len_lookup(self):
        mymodel = CharSetModel.objects.create(field={"red", "expensive"})

        empty = CharSetModel.objects.filter(field__len=0)
        assert empty.count() == 0

        one_or_more = CharSetModel.objects.filter(field__len__gte=1)
        assert one_or_more.count() == 1
        assert one_or_more[0] == mymodel

        two = CharSetModel.objects.filter(field__len=2)
        assert two.count() == 1
        assert two[0] == mymodel

        three = CharSetModel.objects.filter(field__len=3)
        assert three.count() == 0

    def test_char_default(self):
        mymodel = CharSetDefaultModel.objects.create()
        assert mymodel.field == {"a", "d"}

        mymodel = CharSetDefaultModel.objects.get(id=mymodel.id)
        assert mymodel.field == {"a", "d"}

    def test_int_easy(self):
        mymodel = IntSetModel.objects.create(field={1, 2})
        assert mymodel.field == {1, 2}
        mymodel = IntSetModel.objects.get(id=mymodel.id)
        assert mymodel.field == {1, 2}

    def test_int_contains_lookup(self):
        onetwo = IntSetModel.objects.create(field={1, 2})

        ones = IntSetModel.objects.filter(field__contains=1)
        assert ones.count() == 1
        assert ones[0] == onetwo

        twos = IntSetModel.objects.filter(field__contains=2)
        assert twos.count() == 1
        assert twos[0] == onetwo

        threes = IntSetModel.objects.filter(field__contains=3)
        assert threes.count() == 0

        with pytest.raises(ValueError):
            list(IntSetModel.objects.filter(field__contains={1, 2}))

        ones_and_twos = IntSetModel.objects.filter(
            Q(field__contains=1) & Q(field__contains=2)
        )
        assert ones_and_twos.count() == 1
        assert ones_and_twos[0] == onetwo

        ones_and_threes = IntSetModel.objects.filter(
            Q(field__contains=1) & Q(field__contains=3)
        )
        assert ones_and_threes.count() == 0

        ones_or_threes = IntSetModel.objects.filter(
            Q(field__contains=1) | Q(field__contains=3)
        )
        assert ones_or_threes.count() == 1

        no_three = IntSetModel.objects.exclude(field__contains=3)
        assert no_three.count() == 1

        no_one = IntSetModel.objects.exclude(field__contains=1)
        assert no_one.count() == 0


class TestSetF(TestCase):
    def test_add_to_none(self):
        CharSetModel.objects.create(field=set())
        CharSetModel.objects.update(field=SetF("field").add("first"))
        model = CharSetModel.objects.get()
        assert model.field == {"first"}

    def test_add_to_one(self):
        CharSetModel.objects.create(field={"big"})
        CharSetModel.objects.update(field=SetF("field").add("bad"))
        model = CharSetModel.objects.get()
        assert model.field == {"big", "bad"}

    def test_add_to_some(self):
        CharSetModel.objects.create(field={"big", "blue"})
        CharSetModel.objects.update(field=SetF("field").add("round"))
        model = CharSetModel.objects.get()
        assert model.field == {"big", "blue", "round"}

    def test_add_to_multiple_objects(self):
        CharSetModel.objects.create(field={"mouse"})
        CharSetModel.objects.create(field={"keyboard"})
        CharSetModel.objects.update(field=SetF("field").add("screen"))
        first, second = tuple(CharSetModel.objects.all())
        assert first.field == {"mouse", "screen"}
        assert second.field == {"keyboard", "screen"}

    def test_add_exists(self):
        CharSetModel.objects.create(field={"nice"})
        CharSetModel.objects.update(field=SetF("field").add("nice"))
        model = CharSetModel.objects.get()
        assert model.field == {"nice"}

    def test_add_expression(self):
        CharSetModel.objects.create(field={"a"})
        CharSetModel.objects.update(field=SetF("field").add(Value("b")))
        model = CharSetModel.objects.get()
        assert model.field == {"a", "b"}

    @override_mysql_variables(SQL_MODE="ANSI")
    def test_add_works_in_ansi_mode(self):
        CharSetModel.objects.create()
        CharSetModel.objects.update(field=SetF("field").add("big"))
        CharSetModel.objects.update(field=SetF("field").add("bad"))
        model = CharSetModel.objects.get()
        assert model.field == {"big", "bad"}

    def test_add_assignment(self):
        model = CharSetModel.objects.create(field={"red"})
        model.field = SetF("field").add("blue")
        model.save()
        model = CharSetModel.objects.get()
        assert model.field == {"red", "blue"}

    def test_remove_one(self):
        CharSetModel.objects.create(field={"dopey", "knifey"})
        CharSetModel.objects.update(field=SetF("field").remove("knifey"))
        model = CharSetModel.objects.get()
        assert model.field == {"dopey"}

    def test_remove_only_one(self):
        CharSetModel.objects.create(field={"pants"})
        CharSetModel.objects.update(field=SetF("field").remove("pants"))
        model = CharSetModel.objects.get()
        assert model.field == set()

    def test_remove_from_none(self):
        CharSetModel.objects.create(field=set())
        CharSetModel.objects.update(field=SetF("field").remove("jam"))
        model = CharSetModel.objects.get()
        assert model.field == set()

    def test_remove_first(self):
        CharSetModel.objects.create()
        CharSetModel.objects.update(field="a,b,c")
        CharSetModel.objects.update(field=SetF("field").remove("a"))
        model = CharSetModel.objects.get()
        assert model.field == {"b", "c"}

    def test_remove_middle(self):
        CharSetModel.objects.create()
        CharSetModel.objects.update(field="a,b,c")
        CharSetModel.objects.update(field=SetF("field").remove("b"))
        model = CharSetModel.objects.get()
        assert model.field == {"a", "c"}

    def test_remove_last(self):
        CharSetModel.objects.create()
        CharSetModel.objects.update(field="a,b,c")
        CharSetModel.objects.update(field=SetF("field").remove("c"))