from django.test import TestCase

from shop.models import Shop
from shop.sources import container_name_for, owner_characters, source_tree
from shop.tests._corptools import make_asset, make_owner_character

STATION = 60003760
CONTAINER = 900000001


class PickerTests(TestCase):
    def setUp(self):
        self.user, self.audit = make_owner_character()
        self.shop = Shop.objects.create(slug="p", name="P", created_by=self.user)

    def test_owner_characters_returns_users_audits(self):
        self.assertEqual(
            list(owner_characters(self.user).values_list("pk", flat=True)),
            [self.audit.pk],
        )

    def test_source_tree_lists_station_and_container(self):
        make_asset(self.audit, type_id=671, item_id=1, location_id=STATION)
        make_asset(
            self.audit,
            type_id=11488,
            item_id=CONTAINER,
            location_id=STATION,
            name="Loot Box",
        )
        make_asset(self.audit, type_id=671, item_id=2, location_id=CONTAINER)
        tree = source_tree(self.user, self.shop)
        self.assertEqual(len(tree), 1)
        char = tree[0]
        self.assertEqual(char["owner_id"], self.audit.pk)
        station = char["locations"][0]
        self.assertEqual(station["location_id"], STATION)
        self.assertEqual(
            station["containers"], [{"item_id": CONTAINER, "name": "Loot Box"}]
        )

    def test_fitted_ship_is_not_a_container(self):
        from shop.tests._corptools import make_ship_sde_type

        ship_type = make_ship_sde_type(type_id=671)  # category Ship(6)
        # a fitted ship sitting in the hangar, holding a module (module's
        # location_id == the ship's item_id, so the ship "has children")
        make_asset(
            self.audit,
            type_id=671,
            item_id=7001,
            location_id=STATION,
            name="My Titan",
            type_name=ship_type,
        )
        make_asset(self.audit, type_id=222, item_id=7002, location_id=7001)  # module
        tree = source_tree(self.user, self.shop)
        containers = tree[0]["locations"][0]["containers"]
        self.assertNotIn(7001, [c["item_id"] for c in containers])

    def test_container_name_for_reads_asset_name(self):
        make_asset(
            self.audit,
            type_id=11488,
            item_id=CONTAINER,
            location_id=STATION,
            name="Loot Box",
        )
        self.assertEqual(container_name_for(self.audit.pk, CONTAINER), "Loot Box")
