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

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

logger = logging.getLogger('discord_app')

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


class InjuryModel(pydantic.BaseModel):
    season: int
    player_id: int
    total_games: int
    start_week: int
    start_game: int
    end_week: int
    end_game: int
    is_active: bool = True


@router.get('')
@handle_db_errors
async def get_injuries(
        season: list = Query(default=None), player_id: list = Query(default=None), min_games: int = None,
        max_games: int = None, team_id: list = Query(default=None), is_active: bool = None,
        short_output: bool = False, sort: Optional[str] = 'start-asc'):
    all_injuries = Injury.select()

    if season is not None:
        all_injuries = all_injuries.where(Injury.season << season)
    if player_id is not None:
        all_injuries = all_injuries.where(Injury.player_id << player_id)
    if min_games is not None:
        all_injuries = all_injuries.where(Injury.total_games >= min_games)
    if max_games is not None:
        all_injuries = all_injuries.where(Injury.total_games <= max_games)
    if is_active is not None:
        all_injuries = all_injuries.where(Injury.is_active == is_active)
    if team_id is not None:
        all_players = Player.select().where(Player.team_id << team_id)
        all_injuries = all_injuries.where(Injury.player << all_players)

    if sort == 'return-asc':
        all_injuries = all_injuries.order_by(Injury.end_week, Injury.end_game)
    elif sort == 'return-desc':
        all_injuries = all_injuries.order_by(-Injury.end_week, -Injury.end_game)
    elif sort == 'start-asc':
        all_injuries = all_injuries.order_by(Injury.start_week, Injury.start_game)
    elif sort == 'start-desc':
        all_injuries = all_injuries.order_by(-Injury.start_week, -Injury.start_game)

    return_injuries = {
        'count': all_injuries.count(),
        'injuries': [model_to_dict(x, recurse=not short_output) for x in all_injuries]
    }
    db.close()
    return return_injuries


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

    this_injury = Injury.get_or_none(Injury.id == injury_id)
    if this_injury is None:
        db.close()
        raise HTTPException(status_code=404, detail=f'Injury ID {injury_id} not found')

    if is_active is not None:
        this_injury.is_active = is_active

    if this_injury.save() == 1:
        r_injury = model_to_dict(this_injury)
        db.close()
        return r_injury
    else:
        db.close()
        raise HTTPException(status_code=500, detail=f'Unable to patch injury {injury_id}')


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

    this_injury = Injury(**new_injury.dict())

    if this_injury.save():
        r_injury = model_to_dict(this_injury)
        db.close()
        return r_injury
    else:
        db.close()
        raise HTTPException(status_code=500, detail=f'Unable to post injury')


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

    this_injury = Injury.get_or_none(Injury.id == injury_id)
    if this_injury is None:
        db.close()
        raise HTTPException(status_code=404, detail=f'Injury ID {injury_id} not found')

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

    if count == 1:
        return f'Injury {injury_id} has been deleted'
    else:
        raise HTTPException(status_code=500, detail=f'Unable to delete injury {injury_id}')



