from django.utils.translation import gettext_lazy as _

from ocyan.core.fender import config


def price_ranges(default):
    ranges = config.get("oscar_elasticsearch", "price_ranges")
    if ranges is not None:
        return parse_range_definition(ranges)

    return default


def parse_range_definition(range_definition):
    return [
        int(range_str) for range_str in range_definition.split(",") if range_str != ""
    ]


DEFAULT_FACETS = [
    {
        "name": "price",
        "label": _("Price"),
        "type": "range",
        "formatter": "oscar_elasticsearch.search.format.currency",
        "ranges": price_ranges(default=[25, 100, 500, 1000]),
    }
]


def get_facet_config():
    return DEFAULT_FACETS + [
        dict(
            facet,
            name="attrs.%(name)s" % facet,
            type=facet["type"],
            label=facet["label"],
            ranges=parse_range_definition(facet.get("ranges", "")),
        )
        for facet in config.get("oscar_elasticsearch", "facets", [])
    ]
