import re

from server.handlers.api.spots import APISpotsHandler, APISpotsStreamHandler

_GRID_SOURCE_RE = re.compile(r'"dx_location_source":\s*"GRID"')


class V1APISpotsHandler(APISpotsHandler):
    """API request handler for /api/v1/spots (GET). Included in early Spothole v2 for backwards compatibility."""

    def write(self, chunk):
        if isinstance(chunk, str):
            chunk = _GRID_SOURCE_RE.sub('"dx_location_source": "SPOT"', chunk)
        super().write(chunk)

class V1APISpotsStreamHandler(APISpotsStreamHandler):
    """API request handler for /api/v1/spots/stream (SSE). Included in early Spothole v2 for backwards compatibility."""

    def write_message(self, *args, **kwargs):
        args = list(args)
        for i, a in enumerate(args):
            if isinstance(a, str) and '"dx_location_source"' in a:
                args[i] = _GRID_SOURCE_RE.sub('"dx_location_source": "SPOT"', a)
        for k, v in kwargs.items():
            if isinstance(v, str) and '"dx_location_source"' in v:
                kwargs[k] = _GRID_SOURCE_RE.sub('"dx_location_source": "SPOT"', v)
        super().write_message(*args, **kwargs)