from typing import Optional

from fastapi import APIRouter, Depends, Request

from src.depends.services import get_service
from src.model.internal.session import UserSession
from src.model.request.ultmarc_doctor import (UltmarcDoctorInfoModel,
                                              UltmarcDoctorSearchModel)
from src.model.request.ultmarc_inst import (UltmarcInstInfoModel,
                                            UltmarcInstSearchModel)
from src.router.session_router import AuthenticatedRoute
from src.services.batch_status_service import BatchStatusService
from src.services.session_service import set_session
from src.services.ultmarc_view_service import UltmarcViewService
from src.templates import templates

router = APIRouter()
router.route_class = AuthenticatedRoute

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

#########################
# アルトマーク施設検索    #
#########################


@router.get('/instSearch')
def ultmarc_inst_view(
    request: Request,
    batch_status_service: BatchStatusService = Depends(get_service(BatchStatusService)),
    ultmarc_service: UltmarcViewService = Depends(get_service(UltmarcViewService))
):
    session: UserSession = request.session
    # バッチ処理中ステータスを取得
    is_batch_processing = batch_status_service.is_batch_processing()

    # 検索項目の取得（都道府県・施設区分）
    ultmarc = ultmarc_service.prepare_ultmarc_inst_search_view()
    ultmarc.is_batch_processing = is_batch_processing

    # セッション書き換え
    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(
        'instSearch.html', {
            'request': request,
            'ultmarc': ultmarc,
        },
        headers={'session_key': session_key}
    )
    return templates_response


@router.post('/instSearch')
def search_inst(
    request: Request,
    ultmarc_inst_form: Optional[UltmarcInstSearchModel] = Depends(UltmarcInstSearchModel.as_form),
    ultmarc_service: UltmarcViewService = Depends(get_service(UltmarcViewService)),
    batch_status_service: BatchStatusService = Depends(get_service(BatchStatusService))
):
    session: UserSession = request.session

    # バッチ処理中ステータスを取得
    is_batch_processing = batch_status_service.is_batch_processing()

    # 施設データを検索
    ultmarc_inst_data = ultmarc_service.search_inst_data(ultmarc_inst_form)

    # 検索項目の取得（都道府県・施設区分）
    ultmarc = ultmarc_service.prepare_ultmarc_inst_search_view()
    ultmarc.is_batch_processing = is_batch_processing
    ultmarc.inst_data = ultmarc_inst_data
    # 画面表示用にエスケープを解除して返す
    ultmarc.form_data = ultmarc_inst_form.unescape()

    # セッション書き換え
    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(
        'instSearch.html', {
            'request': request,
            'ultmarc': ultmarc,
        },
        headers={'session_key': session_key}
    )
    return templates_response

#########################
# アルトマーク施設詳細    #
#########################


@router.get('/instInfo')
def ultmarc_inst_info_view(
    request: Request,
    id: str,
    batch_status_service: BatchStatusService = Depends(get_service(BatchStatusService)),
    ultmarc_service: UltmarcViewService = Depends(get_service(UltmarcViewService))
):
    session: UserSession = request.session
    # バッチ処理中ステータスを取得
    is_batch_processing = batch_status_service.is_batch_processing()

    # 施設情報の取得
    ultmarc = ultmarc_service.prepare_ultmarc_inst_info_view(id)
    # バッチ起動判定
    ultmarc.is_batch_processing = is_batch_processing
    # inst_id
    ultmarc.inst_id = id
    # ページ総数（件数）
    ultmarc.post_cnt = 1
    # ページ数（表示するページNo）
    ultmarc.page_num = 0

    # セッション書き換え
    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(
        'instInfo.html', {
            'request': request,
            'ultmarc': ultmarc,
        },
        headers={'session_key': session_key}
    )
    return templates_response


@router.post('/instInfo')
def ultmarc_inst_info_search(
    request: Request,
    ultmarc_inst_form: Optional[UltmarcInstInfoModel] = Depends(UltmarcInstInfoModel.as_form),
    ultmarc_service: UltmarcViewService = Depends(get_service(UltmarcViewService)),
    batch_status_service: BatchStatusService = Depends(get_service(BatchStatusService))
):
    session: UserSession = request.session
    # バッチ処理中ステータスを取得
    is_batch_processing = batch_status_service.is_batch_processing()

    inst_id = ultmarc_inst_form.inst_id.split(',')

    # 施設情報の取得
    ultmarc = ultmarc_service.prepare_ultmarc_inst_info_view(inst_id[ultmarc_inst_form.page_num])

    # バッチ起動判定の取得
    ultmarc.is_batch_processing = is_batch_processing
    # inst_id
    ultmarc.inst_id = ultmarc_inst_form.inst_id
    # ページ総数（件数）
    ultmarc.post_cnt = len(inst_id)
    # ページ数（表示するページNo）
    ultmarc.page_num = ultmarc_inst_form.page_num

    # セッション書き換え
    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(
        'instInfo.html', {
            'request': request,
            'ultmarc': ultmarc,
        },
        headers={'session_key': session_key}
    )
    return templates_response

#########################
# アルトマーク医師検索    #
#########################


@router.get('/docSearch')
def ultmarc_doctor_view(
    request: Request,
    batch_status_service: BatchStatusService = Depends(get_service(BatchStatusService)),
    ultmarc_service: UltmarcViewService = Depends(get_service(UltmarcViewService))
):
    session: UserSession = request.session
    # バッチ処理中ステータスを取得
    is_batch_processing = batch_status_service.is_batch_processing()

    # 検索項目の取得(都道府県)
    ultmarc = ultmarc_service.prepare_ultmarc_doctor_search_view()
    ultmarc.is_batch_processing = is_batch_processing

    # セッション書き換え
    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(
        'docSearch.html', {
            'request': request,
            'ultmarc': ultmarc,
        },
        headers={'session_key': session_key}
    )
    return templates_response


@router.post('/docSearch')
def search_doc(
    request: Request,
    ultmarc_doctor_form: Optional[UltmarcDoctorSearchModel] = Depends(UltmarcDoctorSearchModel.as_form),
    ultmarc_service: UltmarcViewService = Depends(get_service(UltmarcViewService)),
    batch_status_service: BatchStatusService = Depends(get_service(BatchStatusService))
):
    session: UserSession = request.session

    # バッチ処理中ステータスを取得
    is_batch_processing = batch_status_service.is_batch_processing()

    # 医師データを検索
    ultmarc_doctor_data = ultmarc_service.search_doctor_data(ultmarc_doctor_form)

    # 検索項目などのデータを取得
    ultmarc = ultmarc_service.prepare_ultmarc_doctor_search_view()
    ultmarc.is_batch_processing = is_batch_processing
    ultmarc.doctor_data = ultmarc_doctor_data
    # 画面表示用にエスケープを解除して返す
    ultmarc.form_data = ultmarc_doctor_form.unescape()

    # セッション書き換え
    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(
        'docSearch.html', {
            'request': request,
            'ultmarc': ultmarc,
        },
        headers={'session_key': session_key}
    )
    return templates_response

#########################
# アルトマーク医師詳細    #
#########################


@router.get('/docInfo')
def ultmarc_doctor_info_view(
    request: Request,
    id: str,
    batch_status_service: BatchStatusService = Depends(get_service(BatchStatusService)),
    ultmarc_service: UltmarcViewService = Depends(get_service(UltmarcViewService))
):
    session: UserSession = request.session
    # バッチ処理中ステータスを取得
    is_batch_processing = batch_status_service.is_batch_processing()

    # 医師情報の取得
    ultmarc = ultmarc_service.prepare_ultmarc_doctor_info_view(id)
    # バッチ起動判定の取得
    ultmarc.is_batch_processing = is_batch_processing
    # doc_id
    ultmarc.doc_id = id
    # ページ総数（件数）
    ultmarc.post_cnt = 1
    # ページ数（表示するページNo）
    ultmarc.page_num = 0

    # セッション書き換え
    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(
        'docInfo.html', {
            'request': request,
            'ultmarc': ultmarc,
        },
        headers={'session_key': session_key}
    )
    return templates_response


@router.post('/docInfo')
def ultmarc_doctor_info_search(
    request: Request,
    ultmarc_doctor_form: Optional[UltmarcDoctorInfoModel] = Depends(UltmarcDoctorInfoModel.as_form),
    ultmarc_service: UltmarcViewService = Depends(get_service(UltmarcViewService)),
    batch_status_service: BatchStatusService = Depends(get_service(BatchStatusService))
):
    session: UserSession = request.session
    # バッチ処理中ステータスを取得
    is_batch_processing = batch_status_service.is_batch_processing()

    doc_id = ultmarc_doctor_form.doc_id.split(',')

    # 医師情報の取得
    ultmarc = ultmarc_service.prepare_ultmarc_doctor_info_view(doc_id[ultmarc_doctor_form.page_num])
    # バッチ起動判定の取得
    ultmarc.is_batch_processing = is_batch_processing
    # doc_id
    ultmarc.doc_id = ultmarc_doctor_form.doc_id
    # ページ総数（件数）
    ultmarc.post_cnt = len(doc_id)
    # ページ数（表示するページNo）
    ultmarc.page_num = ultmarc_doctor_form.page_num

    # セッション書き換え
    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(
        'docInfo.html', {
            'request': request,
            'ultmarc': ultmarc,
        },
        headers={'session_key': session_key}
    )
    return templates_response
