import re

import mercantile

# This regular expression describe a pattern for {zoom}/{x}/{y} format.
ZXY_SEGMENT_NAME_FORMAT_RE = re.compile("[0-9]+/[0-9]+/[0-9]+$")


def is_zxy_segment_name_format(segment_name_to_check):
    """
    Checks if the segment name is of the {zoom}/{x}/{y} format of map tile description.
    """
    if type(segment_name_to_check) is not str:
        return False

    return bool(ZXY_SEGMENT_NAME_FORMAT_RE.match(segment_name_to_check))


def get_tile_bounding_box(zxy_string):
    """
    For a given string of "{zoom}/{x}/{y}" format that depicts a map tile,
    returns LngLatBbox object (class in mercantile) that holds the north, south, east,
    west values that defines the bounding box for the tile.
    """
    z, x, y = (int(num_str) for num_str in zxy_string.split("/"))
    return mercantile.bounds(x, y, z)


def get_geojson_from_zxy(zxy_string):
    """
    Returns a geojson that depict a map tile, based on the given {zoom}/{x}/{y} string.
    """
    tile_bounding_box = get_tile_bounding_box(zxy_string)

    geojson_polygon = {
        "type": "Polygon",
        "coordinates": [
            [
                (tile_bounding_box.west, tile_bounding_box.north),
                (tile_bounding_box.east, tile_bounding_box.north),
                (tile_bounding_box.east, tile_bounding_box.south),
                (tile_bounding_box.west, tile_bounding_box.south),
            ]
        ],
    }

    return geojson_polygon
