from typing import Optional

from fastapi import APIRouter, Depends, HTTPException, Request
from starlette import status

from src.depends.services import get_service
from src.logging.get_logger import get_logger
from src.model.internal.session import UserSession
from src.model.request.bio import BioModel
from src.model.view.bio_view_model import BioViewModel
from src.router.session_router import AuthenticatedRoute
from src.services.batch_status_service import BatchStatusService
from src.services.bio_view_service import BioViewService
from src.services.session_service import set_session
from src.system_var import constants
from src.templates import templates

router = APIRouter()
router.route_class = AuthenticatedRoute
logger = get_logger('生物由来参照')

#########################
# Views                 #
#########################


@router.get('/BioSearchList')
def bio_view(
    request: Request,
    batch_status_service: BatchStatusService = Depends(get_service(BatchStatusService)),
    bio_service: BioViewService = Depends(get_service(BioViewService))
):
    session: UserSession = request.session
    # バッチ処理中の場合、機能を利用させない
    if batch_status_service.is_batch_processing():
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=constants.LOGOUT_REASON_BATCH_PROCESSING)

    logger.debug(f'UserId: {session.user_id}')
    # 検索項目の取得
    bio = bio_service.prepare_bio_view(session)
    # セッション書き換え
    session.update(
        actions=[
            UserSession.last_access_time.set(UserSession.new_last_access_time()),
            UserSession.record_expiration_time.set(UserSession.new_record_expiration_time()),
        ]
    )
    session_key = set_session(session)
    templates_response = templates.TemplateResponse(
        'bioSearchList.html', {
            'request': request,
            'bio': bio,
        },
        headers={'session_key': session_key}
    )
    return templates_response


@router.post('/BioSearchList')
def search_bio(
    request: Request,
    bio_form: Optional[BioModel] = Depends(BioModel.as_form),
    bio_service: BioViewService = Depends(get_service(BioViewService)),
    batch_status_service: BatchStatusService = Depends(get_service(BatchStatusService))
):
    session: UserSession = request.session
    # バッチ処理中の場合、機能を利用させない
    if batch_status_service.is_batch_processing():
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=constants.LOGOUT_REASON_BATCH_PROCESSING)

    # 生物由来データを検索
    bio_sales_view_data = bio_service.search_bio_data(bio_form)
    # 検索項目などのデータを取得
    bio: BioViewModel = bio_service.prepare_bio_view(session)
    bio.bio_data = bio_sales_view_data
    bio.form_data = bio_form
    # セッション書き換え
    session.update(
        actions=[
            UserSession.last_access_time.set(UserSession.new_last_access_time()),
            UserSession.record_expiration_time.set(UserSession.new_record_expiration_time()),
        ]
    )
    session_key = set_session(session)
    templates_response = templates.TemplateResponse(
        'bioSearchList.html', {
            'request': request,
            'bio': bio
        },
        headers={'session_key': session_key}
    )
    return templates_response
