import cfgtools
import logging
import os

from datetime import datetime
from typing import Optional, Tuple

from mw_helper import show_message_dialog

from actions.fiscal import get_nf_type
from application.interactor import FiscalWrapperInteractor


NFCE_TYPE = "NFCE"
IS_NFCE = None

alert_certificate_expiration = True
certificate_expiration_days = None      # type: Optional[int]
last_updated_date = None                # type: Optional[datetime]
first_alert_expiration_days = None      # type: Optional[int]
second_alert_expiration_days = None     # type: Optional[int]

logger = logging.getLogger("PosActions")


def check_certificate(
        pos_id,             # type: int
):
    # type: (...) -> None

    global alert_certificate_expiration

    if not _check_is_nfce():
        return

    now = datetime.now()
    if not last_updated_date or (now - last_updated_date).days >= 1:
        alert_certificate_expiration = True
        _set_certificate_expiration_days(now)

    first_alert_days, second_alert_days = _get_certificate_alert_days()

    ignore_alert = certificate_expiration_days > first_alert_days
    if ignore_alert:
        return

    must_show_first_alert = certificate_expiration_days >= second_alert_days and alert_certificate_expiration
    must_show_second_alert = certificate_expiration_days < second_alert_days
    if must_show_first_alert or must_show_second_alert:
        alert_certificate_expiration = False
        show_message_dialog(pos_id, message="$ALERT_CERTIFICATE_EXPIRATION_DAYS|{}".format(certificate_expiration_days))


def _check_is_nfce():
    # type: (...) -> bool

    global IS_NFCE

    if IS_NFCE is None:
        IS_NFCE = get_nf_type() == NFCE_TYPE

    return IS_NFCE


def _set_certificate_expiration_days(
    updated_time,   # type: datetime
):
    # type: (...) -> None

    global certificate_expiration_days
    global last_updated_date

    logger.info("Getting certificate expiration time")

    last_updated_date = updated_time.replace(hour=0, minute=0, second=0, microsecond=0)
    fiscal_wrapper_interactor = FiscalWrapperInteractor()
    try:
        certificate_expiration_days = fiscal_wrapper_interactor.get_certificate_expiration_days()
    except Exception:
        logger.exception("Error getting certificate expiration time")


def _get_certificate_alert_days():
    # type: (...) -> Tuple[int, int]

    global first_alert_expiration_days, second_alert_expiration_days

    if first_alert_expiration_days is None or second_alert_expiration_days is None:
        config = cfgtools.read(os.environ["LOADERCFG"])
        config_path = "Customizations.CertificateExpiration"
        first_alert_expiration_days = int(config.find_value(config_path + ".FirstAlertDays") or 15)
        second_alert_expiration_days = int(config.find_value(config_path + ".SecondAlertDays") or 3)

    return first_alert_expiration_days, second_alert_expiration_days
