import os
import json
import cfgtools
import sysactions
import logging

from cfgtools import Configuration
from typing import Union

logger = logging.getLogger("PosActions")
ask_document_pinpad = {}
request_void_reason_on = None
config = None
cancel_json = None


def get_config():
    # type: (...) -> Configuration

    global config

    if config is None:
        config = cfgtools.read(os.environ["LOADERCFG"])

    return config


def read_int_value_from_loader(
    loader,             # type: Configuration
    key,                # type: str
    default_value,      # type: int
):
    # type: (...) -> int

    try:
        value = int(loader.find_value(key))
        return value
    except (Exception,):
        return default_value


def get_ask_document_pinpad(
    pos_id,  # type: Union[int, str]
):
    # type: (...) -> bool

    global ask_document_pinpad

    pos_id = str(pos_id)
    if pos_id not in ask_document_pinpad:
        ask_document = sysactions.get_cfg(posid=pos_id).find_value("AskDocumentPinpad", "false").lower() == "true"
        ask_document_pinpad[pos_id] = ask_document

    return ask_document_pinpad[pos_id]


def must_require_void_reason(
    void_on,    # type: str
):
    # type: (...) -> bool

    global request_void_reason_on

    if request_void_reason_on is None:
        config_key = get_config().find_values("Customizations.requestVoidReasonOn")
        if config_key is not None:
            request_void_reason_on = config_key
        else:
            request_void_reason_on = ["VOID_CURRENT_ORDER"]

    return void_on in request_void_reason_on


def get_cancel_json():
    # type: (...) -> dict

    global cancel_json

    if cancel_json is None:
        json_path = os.path.join(
            os.environ.get('BUNDLEDIR'),
            "cancel.json",
        )
        if not os.path.exists(json_path):
            cancel_json = {}

        try:
            with open(json_path, "rb") as f:
                cancel_json = json.loads(f.read().decode("utf-8"))
        except Exception as e:
            logger.error(e)
            cancel_json = {}

    return cancel_json
