import json
import logging

from typing import Optional

from modelcommon.fiscalwrapper import FiscalizationException
from sysactions import send_message
from msgbus import (
    TK_SYS_ACK,
    FM_PARAM,
)
from model.customexception import (
    ErrorGettingNFType,
    ErrorGettingCertificateExpirationDays
)
from bustoken import (
    TK_FISCALWRAPPER_GET_NF_TYPE,
    TK_FISCALWRAPPER_GET_CERTIFICATE_EXPIRATION_DAYS,
    TK_FISCALWRAPPER_CAN_FISCALIZE_ORDER,
)


class FiscalWrapperInteractor(object):

    def __init__(self):
        self.logger = logging.getLogger("PosActions")

    @staticmethod
    def get_nf_type():
        # type: () -> str

        response = send_message("FiscalWrapper", TK_FISCALWRAPPER_GET_NF_TYPE, FM_PARAM, None, timeout=30000000)
        if response.token == TK_SYS_ACK:
            return response.data.upper()

        raise ErrorGettingNFType(response.data)

    @staticmethod
    def get_certificate_expiration_days():
        # type: () -> int

        response = send_message(
            dest_name="FiscalWrapper",
            token=TK_FISCALWRAPPER_GET_CERTIFICATE_EXPIRATION_DAYS,
            format=FM_PARAM,
            data='',
            timeout=30000000,
        )

        if response.token == TK_SYS_ACK:
            return int(response.data)

        raise ErrorGettingCertificateExpirationDays(response.data)

    @staticmethod
    def can_fiscalize_order(
        total_gross=0,  # type: Optional[float]
        tip_amount=0,   # type: Optional[float]
    ):
        # type: (...) -> None

        data = "\0".join(map(str, [total_gross, tip_amount]))
        response = send_message(
            dest_name="FiscalWrapper",
            token=TK_FISCALWRAPPER_CAN_FISCALIZE_ORDER,
            format=FM_PARAM,
            data=data,
        )

        if response.token == TK_SYS_ACK:
            return

        response = json.loads(response.data) or "{}"

        raise FiscalizationException(
            error_code=response.get("error_code", ""),
            message=response.get("message", ""),
        )
