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

from ..db_engine import db, Result, Team, model_to_dict, chunked
from ..dependencies import oauth2_scheme, valid_token, PRIVATE_IN_SCHEMA, handle_db_errors

logger = logging.getLogger('discord_app')

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


class ResultModel(pydantic.BaseModel):
    week: int
    game: int
    awayteam_id: int
    hometeam_id: int
    awayscore: int
    homescore: int
    season: int
    scorecard_url: Optional[str] = None


class ResultList(pydantic.BaseModel):
    results: List[ResultModel]


@router.get('')
@handle_db_errors
async def get_results(
        season: int, team_abbrev: list = Query(default=None), week_start: Optional[int] = None,
        week_end: Optional[int] = None, game_num: list = Query(default=None),
        away_abbrev: list = Query(default=None), home_abbrev: list = Query(default=None),
        short_output: Optional[bool] = False):
    all_results = Result.select_season(season)

    if team_abbrev is not None:
        team_list = []
        for x in team_abbrev:
            team_list.append(Team.get_season(x, season))
        all_results = all_results.where(
            (Result.awayteam << team_list) | (Result.hometeam << team_list)
        )

    if away_abbrev is not None:
        team_list = []
        for x in away_abbrev:
            team_list.append(Team.get_season(x, season))
        all_results = all_results.where(Result.awayteam << team_list)

    if home_abbrev is not None:
        team_list = []
        for x in home_abbrev:
            team_list.append(Team.get_season(x, season))
        all_results = all_results.where(Result.hometeam << team_list)

    if game_num is not None:
        all_results = all_results.where(Result.game << game_num)

    if week_start is not None:
        all_results = all_results.where(Result.week >= week_start)

    if week_end is not None:
        all_results = all_results.where(Result.week <= week_end)

    return_results = {
        'count': all_results.count(),
        'results': [model_to_dict(x, recurse=not short_output) for x in all_results]
    }
    db.close()
    return return_results


@router.get('/{result_id}')
@handle_db_errors
async def get_one_result(result_id: int, short_output: Optional[bool] = False):
    this_result = Result.get_or_none(Result.id == result_id)
    if this_result is not None:
        r_result = model_to_dict(this_result, recurse=not short_output)
    else:
        r_result = None
    db.close()
    return r_result


@router.patch('/{result_id}', include_in_schema=PRIVATE_IN_SCHEMA)
@handle_db_errors
async def patch_result(
        result_id: int, week_num: Optional[int] = None, game_num: Optional[int] = None,
        away_team_id: Optional[int] = None, home_team_id: Optional[int] = None, away_score: Optional[int] = None,
        home_score: Optional[int] = None, season: Optional[int] = None, scorecard_url: Optional[str] = None,
        token: str = Depends(oauth2_scheme)):
    if not valid_token(token):
        logger.warning(f'patch_player - Bad Token: {token}')
        raise HTTPException(status_code=401, detail='Unauthorized')

    this_result = Result.get_or_none(Result.id == result_id)
    if this_result is None:
        raise HTTPException(status_code=404, detail=f'Result ID {result_id} not found')

    if week_num is not None:
        this_result.week = week_num

    if game_num is not None:
        this_result.game = game_num

    if away_team_id is not None:
        this_result.awayteam_id = away_team_id

    if home_team_id is not None:
        this_result.hometeam_id = home_team_id

    if away_score is not None:
        this_result.awayscore = away_score

    if home_score is not None:
        this_result.homescore = home_score

    if season is not None:
        this_result.season = season

    if scorecard_url is not None:
        this_result.scorecard_url = scorecard_url

    if this_result.save() == 1:
        r_result = model_to_dict(this_result)
        db.close()
        return r_result
    else:
        db.close()
        raise HTTPException(status_code=500, detail=f'Unable to patch result {result_id}')


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

    new_results = []
    for x in result_list.results:
        if Team.get_or_none(Team.id == x.awayteam_id) is None:
            raise HTTPException(status_code=404, detail=f'Team ID {x.awayteam_id} not found')
        if Team.get_or_none(Team.id == x.hometeam_id) is None:
            raise HTTPException(status_code=404, detail=f'Team ID {x.hometeam_id} not found')

        new_results.append(x.dict())

    with db.atomic():
        for batch in chunked(new_results, 15):
            Result.insert_many(batch).on_conflict_ignore().execute()
    db.close()

    return f'Inserted {len(new_results)} results'


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

    this_result = Result.get_or_none(Result.id == result_id)
    if not this_result:
        db.close()
        raise HTTPException(status_code=404, detail=f'Result ID {result_id} not found')

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

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


