from time import time

from fastapi import APIRouter

from app import mongo
from app.utils.response_util import response

router = APIRouter()


@router.get("/{board_id}", tags=[""])
async def get(board_id: int):
    start_time = time()

    boards = await mongo.boards_collection.find({
        "projectId": board_id
    }, {
        "_id": False
    }).to_list()

    for board in boards:
        board["project"] = await mongo.projects_collection.find({
            "id": board["projectId"]
        }, {
            "_id": False
        }).to_list()

        board["dealStatuses"] = await mongo.statuses_collection.find({
            "boardId": board["id"]
        }, {
            "_id": False
        }).to_list()

    return response({
        "boards": boards
    }, start_time=start_time)


@router.post("/", tags=[""])
async def post(params: dict):
    start_time = time()
    data = params["board"]

    data["id"] = await mongo.get_next_id(mongo.boards_collection)

    await mongo.boards_collection.insert_one(data)

    return response({
        "message": "Доска создана",
        "ok": True
    }, start_time=start_time)


@router.patch("/", tags=[""])
async def patch(params: dict):
    start_time = time()
    data = params["board"]

    await mongo.boards_collection.update_one({
        "id": data["id"]
    }, {
        "$set": data
    })

    return response({
        "message": "Доска обновлена",
        "ok": True
    }, start_time=start_time)


@router.delete("/{board_id}", tags=[""])
async def delete(board_id: int):
    start_time = time()

    await mongo.boards_collection.delete_one({
        "id": board_id
    })

    return response({
        "message": "Доска удален",
        "ok": True
    }, start_time=start_time)
