import re

from rr.blocks.main import GridChoiceBlock

from .map import convert_blocks

VALID_GRID_CHOICES = [g[0] for g in GridChoiceBlock.choices]

OFFSET_SANITISATION_REGEX = re.compile(r"col-(?P<size>.*)-offset-(?P<cols>\d)")
COL_SANITISATION_REGEX = re.compile(r"col-(:?xs|sm)")


def offset_pattern_replace(grid):
    return "offset-%(size)s-%(cols)s" % grid.groupdict()


def sanitise_grid(grid):
    grid_classes = []
    block_classes = []
    for value in grid.strip().split(" "):
        value = OFFSET_SANITISATION_REGEX.sub(offset_pattern_replace, value)
        value = COL_SANITISATION_REGEX.sub("col", value)
        if not value:
            continue
        if value in VALID_GRID_CHOICES:
            grid_classes.append(value)
        elif "offset" in value:
            block_classes.append(value)
        else:
            raise ValueError("wat is deze '%s'" % value)

    return " ".join(grid_classes), " ".join(block_classes)


def convert_item_value(obj):
    grid, block_classes = sanitise_grid(obj["grid"])
    obj["grid"] = grid or "col-12"
    if obj["styling"]["block_classes"]:
        obj["styling"]["block_classes"] = "%s %s" % (
            obj["styling"]["block_classes"],
            block_classes,
        )
    else:
        obj["styling"]["block_classes"] = block_classes

    return convert_blocks(obj)
