"""Source-tree tests."""

from django.test import TestCase

from memberaudit.models import CharacterAsset, Location

from shop.sources import owner_characters, source_tree
from shop.tests.test_stock import make_container_type, make_owner_character, make_ship_type


class SourceTreeTests(TestCase):
    def setUp(self):
        self.user, self.char = make_owner_character()
        self.station = Location.objects.create(id=60003760, name="Jita IV-4")
        self.ship = make_ship_type()

    def test_owner_characters_scoped(self):
        make_owner_character("bob", char_id=2002)
        self.assertEqual([c.id for c in owner_characters(self.user)], [self.char.id])

    def test_tree_lists_station(self):
        CharacterAsset.objects.create(
            character=self.char, item_id=1, eve_type=self.ship, is_singleton=True,
            location_flag="Hangar", quantity=1, location=self.station,
        )
        tree = source_tree(self.user)
        self.assertEqual(len(tree), 1)
        self.assertEqual(tree[0]["stations"][0]["name"], "Jita IV-4")

    def test_tree_lists_container(self):
        cont_type = make_container_type()
        container = CharacterAsset.objects.create(
            character=self.char, item_id=500, eve_type=cont_type, is_singleton=True,
            location_flag="Hangar", quantity=1, location=self.station, name="My Box",
        )
        CharacterAsset.objects.create(
            character=self.char, item_id=2, eve_type=self.ship, is_singleton=True,
            location_flag="Hangar", quantity=1, parent=container,
        )
        tree = source_tree(self.user)
        containers = tree[0]["stations"][0]["containers"]
        self.assertEqual(containers, [{"item_id": 500, "name": "My Box"}])

    def test_fitted_ship_is_not_a_container(self):
        # a ship (category 6) with a fitted module has children, but must NOT be a container
        fitted = CharacterAsset.objects.create(
            character=self.char, item_id=900, eve_type=self.ship, is_singleton=True,
            location_flag="Hangar", quantity=1, location=self.station,
        )
        module = make_ship_type(type_id=12056, name="1MN Afterburner", group_id=46,
                                group_name="Propulsion Module", category_id=7, category_name="Module")
        CharacterAsset.objects.create(
            character=self.char, item_id=901, eve_type=module, is_singleton=False,
            location_flag="LoSlot0", quantity=1, parent=fitted,
        )
        tree = source_tree(self.user)
        self.assertEqual(tree[0]["stations"][0]["containers"], [])
