from django.conf import settings

from oscar_elasticsearch.search import update as oscar

from ocyan.core.utils import chunked

from . import spooler


class UpdateIndex(oscar.UpdateIndex):
    def synchronize_searchindex(self, **kwargs):
        if self._categories or self._products:
            categories = list(self._categories)
            self._categories = set()
            products = list(self._products)
            self._products = set()

            # We chunk the spooler files because there is a maximum lenght of the spooler files.
            if products:
                for chunk in chunked(
                    products,
                    settings.OSCAR_ELASTICSEARCH_INDEX_UPDATE_SPOOLER_CHUNK_SIZE,
                ):
                    spooler.update_index_products.spool(*chunk)
            if categories:
                for chunk in chunked(
                    categories,
                    settings.OSCAR_ELASTICSEARCH_INDEX_UPDATE_SPOOLER_CHUNK_SIZE,
                ):
                    spooler.update_index_categories.spool(*chunk)
