from typing import (
    Dict,
    List,
)

from actions.functions.do_transfer import (
    get_sold_amount_by_tender_type,
    save_inserted_values,
)
from actions.models import CloseOperator
from application.repository import PosCtrlRepository


class MissingLogoutInfoInteractor(object):

    def __init__(
        self,                   # type: MissingLogoutInfoInteractor
        pos_ctrl_repository,    # type: PosCtrlRepository
    ):
        # type: (...) -> None

        self.pos_ctrl_repository = pos_ctrl_repository

    def fill_missing_logout_info(
        self,               # type: MissingLogoutInfoInteractor
        business_period,    # type: str
    ):
        # type: (...) -> None

        sessions_by_period = self.pos_ctrl_repository.get_all_session_ids_by_business_period(
            business_period=business_period,
        )

        for session in sessions_by_period:
            session_id = session.session_id
            sold_amount_by_tender_type = get_sold_amount_by_tender_type(session_id=session_id)
            operator_values = self._fill_operator_values(sold_amount_by_tender_type=sold_amount_by_tender_type)

            operator = CloseOperator(
                pos_id=session.pos_id,
                values=operator_values,
                envelope="",
                session=session.session_id,
                payments=sold_amount_by_tender_type,
                manager_id="",
                period=business_period,
            )
            save_inserted_values(operator=operator)

    @staticmethod
    def _fill_operator_values(
        sold_amount_by_tender_type,     # type: Dict[int, List[Dict]]
    ):
        # type: (...) -> List[Dict]

        operator_values = []
        for sold_by_tender in sold_amount_by_tender_type.values():
            tender_id = sold_by_tender[0]["tenderId"]
            operator_value = {
                "tenderId": tender_id,
                "amount": 0.0,
            }
            operator_values.append(operator_value)

        return operator_values
