import datetime

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

from ..db_engine import db, DraftData, model_to_dict
from ..dependencies import oauth2_scheme, valid_token, PRIVATE_IN_SCHEMA, handle_db_errors

logger = logging.getLogger('discord_app')

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


class DraftDataModel(pydantic.BaseModel):
    currentpick: int
    timer: bool
    pick_deadline: datetime.datetime
    result_channel_id: int
    ping_channel_id: int
    pick_minutes: int


@router.get('')
@handle_db_errors
async def get_draftdata():
    draft_data = DraftData.get_or_none()

    if draft_data is not None:
        r_data = model_to_dict(draft_data)
        db.close()
        return r_data

    raise HTTPException(status_code=404, detail=f'No draft data found')


@router.patch('/{data_id}', include_in_schema=PRIVATE_IN_SCHEMA)
@handle_db_errors
async def patch_draftdata(
        data_id: int, currentpick: Optional[int] = None, timer: Optional[bool] = None,
        pick_deadline: Optional[datetime.datetime] = None, result_channel: Optional[int] = None,
        ping_channel: Optional[int] = None, pick_minutes: Optional[int] = None, token: str = Depends(oauth2_scheme)):
    if not valid_token(token):
        logger.warning(f'patch_draftdata - Bad Token: {token}')
        raise HTTPException(status_code=401, detail='Unauthorized')

    draft_data = DraftData.get_or_none(DraftData.id == data_id)
    if draft_data is None:
        db.close()
        raise HTTPException(status_code=404, detail=f'No draft data found')

    if currentpick is not None:
        draft_data.currentpick = currentpick
    if timer is not None:
        draft_data.timer = timer
    if pick_deadline is not None:
        draft_data.pick_deadline = pick_deadline
    if result_channel is not None:
        draft_data.result_channel = result_channel
    if ping_channel is not None:
        draft_data.ping_channel = ping_channel
    if pick_minutes is not None:
        draft_data.pick_minutes = pick_minutes

    saved = draft_data.save()
    r_data = model_to_dict(draft_data)
    db.close()

    if saved == 1:
        return r_data
    else:
        raise HTTPException(status_code=500, detail='Updating draft data failed')

