from aiohttp.web import Request, Response

from maps_adv.warden.common.schemas import (
    CreateTaskInputProtoSchema,
    TaskDetailsProtoSchema,
    UpdateTaskInputProtoSchema,
    UpdateTaskOutputProtoSchema,
    with_proto_schemas,
)
from maps_adv.warden.server.lib.domains.tasks import Domain

__all__ = ["Resources"]


class ApiProvider:
    __slots__ = ("_domain",)

    _domain: Domain

    def __init__(self, domain: Domain):
        self._domain = domain

    @with_proto_schemas(CreateTaskInputProtoSchema, TaskDetailsProtoSchema)
    async def create_task(self, **kwargs) -> dict:
        return await self._domain.create_task(**kwargs)

    @with_proto_schemas(UpdateTaskInputProtoSchema, UpdateTaskOutputProtoSchema)
    async def update_task(self, **kwargs):
        got = await self._domain.update_task(**kwargs)
        if got:
            return {"scheduled_time": got}


class Resources:
    __slots__ = ("_provider",)

    _provider: ApiProvider

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

    async def create_task(self, req: Request) -> Response:
        body = await req.read()

        result = await self._provider.create_task(body)

        return Response(status=201, body=result)

    async def update_task(self, req: Request) -> Response:
        body = await req.read()

        result = await self._provider.update_task(body)

        if not result:
            return Response(status=204)

        return Response(status=200, body=result)
