from fastapi import APIRouter, Depends, Request
from fastapi.responses import HTMLResponse

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.view.menu_view_model import MenuViewModel
from src.model.view.user_view_model import UserViewModel
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.templates import templates

logger = get_logger('MeDaCA機能メニュー')

router = APIRouter()
router.route_class = AuthenticatedRoute

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


@router.get('/', response_class=HTMLResponse)
def menu_view(
    request: Request,
    batch_status_service: BatchStatusService = Depends(get_service(BatchStatusService))
):
    session: UserSession = request.session
    logger.info(f'UserID: {session.user_id}')
    # 日付マスターからバッチ情報を取得する
    hdke_tbl_record = batch_status_service.hdke_table_record

    batch_status = hdke_tbl_record.bch_actf
    dump_status = hdke_tbl_record.dump_sts_kbn
    user = UserViewModel(
        doc_flg=session.doc_flg,
        inst_flg=session.inst_flg,
        bio_flg=session.bio_flg,
        master_mainte_flg=session.master_mainte_flg
    )
    menu = MenuViewModel(
        batch_status=batch_status,
        dump_status=dump_status,
        user_model=user
    )
    # セッション書き換え
    session.update(
        actions=[
            UserSession.last_access_time.set(UserSession.new_last_access_time()),
            UserSession.record_expiration_time.set(UserSession.new_record_expiration_time()),
        ]
    )
    set_session(session)
    templates_response = templates.TemplateResponse(
        'menu.html',
        {
            'request': request,
            'menu': menu
        },
        headers={'session_key': session.session_key}
    )
    return templates_response
