from fastapi import APIRouter, Depends, HTTPException, Query, Response
from typing import List, Optional
import logging
import pydantic

from ..db_engine import db, Keeper, Player, model_to_dict, chunked, fn
from ..dependencies import oauth2_scheme, valid_token, PRIVATE_IN_SCHEMA, handle_db_errors

logger = logging.getLogger('discord_app')

router = APIRouter(
    prefix='/api/v3/keepers',
    tags=['keepers']
)


class KeeperModel(pydantic.BaseModel):
    season: int
    team_id: int
    player_id: int


class KeeperList(pydantic.BaseModel):
    count: Optional[int] = None
    keepers: List[KeeperModel]


@router.get('')
@handle_db_errors
async def get_keepers(
        season: list = Query(default=None), team_id: list = Query(default=None), player_id: list = Query(default=None),
        short_output: bool = False):
    all_keepers = Keeper.select()

    if season is not None:
        all_keepers = all_keepers.where(Keeper.season << season)
    if team_id is not None:
        all_keepers = all_keepers.where(Keeper.team_id << team_id)
    if player_id is not None:
        all_keepers = all_keepers.where(Keeper.player_id << player_id)

    return_keepers = {
        'count': all_keepers.count(),
        'keepers': [model_to_dict(x, recurse=not short_output) for x in all_keepers]
    }
    db.close()
    return return_keepers


@router.patch('/{keeper_id}', include_in_schema=PRIVATE_IN_SCHEMA)
@handle_db_errors
async def patch_keeper(
        keeper_id: int, season: Optional[int] = None, team_id: Optional[int] = None, player_id: Optional[int] = None,
        token: str = Depends(oauth2_scheme)):
    if not valid_token(token):
        logger.warning(f'patch_keeper - Bad Token: {token}')
        raise HTTPException(status_code=401, detail='Unauthorized')

    this_keeper = Keeper.get_or_none(Keeper.id == keeper_id)
    if not this_keeper:
        raise HTTPException(status_code=404, detail=f'Keeper ID {keeper_id} not found')

    if season is not None:
        this_keeper.season = season
    if player_id is not None:
        this_keeper.player_id = player_id
    if team_id is not None:
        this_keeper.team_id = team_id

    if this_keeper.save():
        r_keeper = model_to_dict(this_keeper)
        db.close()
        return r_keeper
    else:
        db.close()
        raise HTTPException(status_code=500, detail=f'Unable to patch keeper {keeper_id}')


@router.post('', include_in_schema=PRIVATE_IN_SCHEMA)
@handle_db_errors
async def post_keepers(k_list: KeeperList, token: str = Depends(oauth2_scheme)):
    if not valid_token(token):
        logger.warning(f'post_keepers - Bad Token: {token}')
        raise HTTPException(status_code=401, detail='Unauthorized')

    new_keepers = []
    for keeper in k_list.keepers:
        new_keepers.append(keeper.dict())

    with db.atomic():
        for batch in chunked(new_keepers, 14):
            Keeper.insert_many(batch).on_conflict_ignore().execute()
    db.close()

    return f'Inserted {len(new_keepers)} keepers'


@router.delete('/{keeper_id}', include_in_schema=PRIVATE_IN_SCHEMA)
@handle_db_errors
async def delete_keeper(keeper_id: int, token: str = Depends(oauth2_scheme)):
    if not valid_token(token):
        logger.warning(f'delete_keeper - Bad Token: {token}')
        raise HTTPException(status_code=401, detail='Unauthorized')

    this_keeper = Keeper.get_or_none(Keeper.id == keeper_id)
    if not this_keeper:
        raise HTTPException(status_code=404, detail=f'Keeper ID {keeper_id} not found')

    count = this_keeper.delete_instance()
    db.close()

    if count == 1:
        return f'Keeper ID {keeper_id} has been deleted'
    else:
        raise HTTPException(status_code=500, detail=f'Keeper ID {keeper_id} could not be deleted')


