from django.db.utils import IntegrityError
from django.test import TestCase

from apps.applets.models import Applet, UserApplet
from apps.applets.utils import applet_context
from apps.lyric.models import User


class AppletModelTest(TestCase):
    def setUp(self):
        self.applet = Applet.objects.create(
            slug="my-applet", name="My Applet", default_visible=True
        )

    def test_applet_can_be_created(self):
        self.assertEqual(Applet.objects.get(slug="my-applet"), self.applet)

    def test_applet_slug_is_unique(self):
        with self.assertRaises(IntegrityError):
            Applet.objects.create(slug="my-applet", name="Second")

    def test_applet_str(self):
        self.assertEqual(str(self.applet), "My Applet")

    def test_applet_grid_defaults(self):
        self.assertEqual(self.applet.grid_cols, 12)
        self.assertEqual(self.applet.grid_rows, 3)


class UserAppletModelTest(TestCase):
    def setUp(self):
        self.user = User.objects.create(email="a@b.cde")
        self.applet, _ = Applet.objects.get_or_create(slug="username", defaults={"name": "Username"})

    def test_user_applet_links_user_to_applet(self):
        ua = UserApplet.objects.create(user=self.user, applet=self.applet, visible=True)
        self.assertIn(ua, self.user.user_applets.all())

    def test_user_applet_unique_per_user_and_applet(self):
        UserApplet.objects.create(user=self.user, applet=self.applet, visible=True)
        with self.assertRaises(IntegrityError):
            UserApplet.objects.create(user=self.user, applet=self.applet, visible=False)

class AppletContextTest(TestCase):
    def setUp(self):
        self.user = User.objects.create(email="a@b.cde")
        self.dash_applet, _ = Applet.objects.get_or_create(slug="username", defaults={"name": "Username", "context": "dashboard"})
        self.game_applet, _ = Applet.objects.get_or_create(slug="new-game", defaults={"name": "New Game", "context": "gameboard"})
    
    def test_filters_by_context(self):
        result = applet_context(self.user, "dashboard")
        slugs = [e["applet"].slug for e in result]
        self.assertIn("username", slugs)
        self.assertNotIn("new-game", slugs)

    def test_defaults_to_applet_default_visible(self):
        result = applet_context(self.user, "dashboard")
        [entry] = [e for e in result if e["applet"].slug == "username"]
        self.assertTrue(entry["visible"])

    def test_respects_user_applet_visible_false(self):
        UserApplet.objects.create(user=self.user, applet=self.dash_applet, visible=False)
        result = applet_context(self.user, "dashboard")
        [entry] = [e for e in result if e["applet"].slug == "username"]
        self.assertFalse(entry["visible"])
