from aiohttp.web import Request, Response, json_response
from smb.common.pgswim import SwimEngine

from maps_adv.geosmb.marksman.server.lib.domain import Domain

from .providers import ApiProvider

__all__ = ["Resources"]


class Resources:
    _provider: ApiProvider

    def __init__(self, domain: Domain, db: SwimEngine):
        self._provider = ApiProvider(domain)
        self._db = db

    async def ping(self, _: Request) -> Response:
        await self._db.healthcheck()

        return Response(status=204)

    async def add_business(self, request: Request) -> Response:
        data = await request.json()

        await self._provider.add_business(data=data)

        return Response(status=201)

    async def list_business_segments_data(self, request: Request) -> Response:
        try:
            biz_id = int(request.query["biz_id"])
        except (KeyError, ValueError):
            return Response(status=400)

        result = await self._provider.list_business_segments_data(biz_id=biz_id)

        return json_response(data=result)
