import logging

from fastapi import APIRouter, Query
from fastapi.exceptions import HTTPException
from tortoise.expressions import Q

from app.controllers.datasource import datasource_controller
from app.schemas.base import Success, SuccessExtra
from app.schemas.roles import *

logger = logging.getLogger(__name__)
router = APIRouter(prefix="/datasource")


@router.get("/list", summary="查看模板列表")
async def list_role(
    page: int = Query(1, description="页码"),
    limit: int = Query(10, description="每页数量"),
    table_name: str = Query("", description="名称，用于查询"),
):
    # data = await datasource_controller.load_tables()
    # return SuccessExtra(data=data)
    q = Q()
    if table_name:
        q = Q(name__contains=table_name)
    total, role_objs = await datasource_controller.list(page=page, page_size=limit, search=q)
    data = [await obj.to_dict() for obj in role_objs]
    return SuccessExtra(data=data, total=total, page=page, page_size=limit)


@router.get("/get/{table_name}", summary="查看")
async def get_role(table_name):
    data = await datasource_controller.load_tables(name=table_name)
    return SuccessExtra(data=data)


@router.post("/create", summary="创建")
async def create_role(role_in: RoleCreate):
    if await datasource_controller.is_exist(name=role_in.name):
        raise HTTPException(
            status_code=400,
            detail="The role with this rolename already exists in the system.",
        )
    await datasource_controller.create(obj_in=role_in)
    return Success(msg="Created Successfully")


@router.post("/update", summary="更新")
async def update_role(role_in: RoleUpdate):
    await datasource_controller.update(id=role_in.id, obj_in=role_in)
    return Success(msg="Updated Successfully")


@router.delete("/delete", summary="删除")
async def delete_role(
    role_id: int = Query(..., description="ID"),
):
    await datasource_controller.remove(id=role_id)
    return Success(msg="Deleted Success")


@router.get("/authorized", summary="查看权限")
async def get_role_authorized(id: int = Query(..., description="ID")):
    role_obj = await datasource_controller.get(id=id)
    data = await role_obj.to_dict(m2m=True)
    return Success(data=data)


@router.post("/authorized", summary="更新权限")
async def update_role_authorized(role_in: RoleUpdateMenusApis):
    role_obj = await datasource_controller.get(id=role_in.id)
    await datasource_controller.update_roles(role=role_obj, menu_ids=role_in.menu_ids, api_infos=role_in.api_infos)
    return Success(msg="Updated Successfully")
