import odin

from oscar.core.loading import get_class, get_model

from ocyan.main.loading import get_baseclass

ProductResource = get_class("oscar_odin.resources.catalogue", "ProductResource")

ProductElasticSearchResource = get_class(
    "search.mappings.products.resources", "ProductElasticSearchResource"
)

BaseProductMapping = get_baseclass(
    "search.mappings.products.mappings",
    "ProductMapping",
    "ocyan.plugin.oscar_elasticsearch.search",
)
Product = get_model("catalogue", "Product")


class ProductMapping(BaseProductMapping):
    from_resource = ProductResource
    to_resource = ProductElasticSearchResource

    register_mapping = False

    @odin.map_field(from_field="is_public")
    def is_public(self, is_public):
        if self.source.structure == Product.PARENT:
            has_stockrecords = (
                Product.objects.filter(parent_id=self.source.id)
                .filter(stockrecords__isnull=False)
                .exists()
            )
        else:
            has_stockrecords = (
                False if not self.source.price and not self.source.currency else True
            )

        if not has_stockrecords:
            return False

        return is_public
