from aiohttp import web

from maps_adv.points.server.lib.api.resources import (
    ForecastsResources,
    PingResources,
    PointsResources,
)
from maps_adv.points.server.lib.data_managers import (
    ForecastsDataManager,
    PointsDataManager,
)
from maps_adv.points.server.lib.db import DB

from .middlewares import (
    handle_collection_not_found_exception,
    handle_invalid_version_exception,
    handle_points_properties_exception,
    handle_polygon_properties_exception,
    handle_validation_error_exception,
)

__all__ = ["create"]


def create(
    db: DB, points_dm: PointsDataManager, forecasts_dm: ForecastsDataManager
) -> web.Application:
    ping = PingResources(db)
    points = PointsResources(points_dm)
    forecasts = ForecastsResources(forecasts_dm)

    api = web.Application(
        middlewares=[
            handle_collection_not_found_exception,
            handle_polygon_properties_exception,
            handle_invalid_version_exception,
            handle_validation_error_exception,
            handle_points_properties_exception,
        ],
        client_max_size=10240 ** 2,
    )
    api.add_routes(
        [
            web.get("/ping", ping.ping),
            web.post(
                r"/api/v1/points/{type}/{version:\d+}/by-polygons/",
                points.find_within_polygons,
            ),
            web.post("/api/v1/forecasts/billboard/", forecasts.forecast_billboard),
            web.post("/api/v1/forecasts/zerospeed/", forecasts.forecast_zerospeed),
            web.post("/api/v1/forecasts/pins/", forecasts.forecast_pins),
            web.post("/api/v1/forecasts/overview/", forecasts.forecast_overview),
        ]
    )

    return api
