from msgbus import MBEasyContext
from old_helper import BaseRepository
from persistence import Connection
from typing import List

from application.domain import OperatorSession


class PosCtrlRepository(BaseRepository):
    def __init__(
        self,           # type: PosCtrlRepository
        mb_context,     # type: MBEasyContext
    ):

        super(PosCtrlRepository, self).__init__(mb_context)

    def get_all_session_ids_by_business_period(
        self,               # type: PosCtrlRepository
        business_period,    # type: str
    ):
        # type: (...) -> List[OperatorSession]

        def inner_func(
            conn,   # type: Connection
        ):

            sessions_by_period = []
            query = _query_get_session_ids_by_business_period.format(business_period)
            cursor = conn.select(query)
            if cursor.rows() > 0:
                for row in cursor:
                    operator_session = OperatorSession(
                        pos_id=row.get_entry("PosId"),
                        session_id=row.get_entry("SessionId"),
                    )
                    sessions_by_period.append(operator_session)

            return sessions_by_period

        return self.execute_with_connection(method=inner_func)


_query_get_session_ids_by_business_period = """
    SELECT 
        PosId, 
        SessionId
    FROM UserSession 
    WHERE BusinessPeriod = '{}'
"""
