from sysactions import action
from .. import logger

mobile_version = {}


@action
def set_mobile_version_cache(
    pos_id,      # type: str
    version,     # type: str
):
    # type: (...) -> None

    global mobile_version

    logger.debug("Set mobile version. PosId/Version: {}/{}".format(pos_id, version))
    mobile_version[pos_id] = version


def use_function_mobile_reprint(
    pos_id,     # type: str
):
    # type: (...) -> bool

    global mobile_version

    current_mobile_version = mobile_version.get(pos_id, None)
    if not current_mobile_version:
        return False

    return _compare_versions(
        current_version=current_mobile_version,
        required_version="1.21.0.0",
    ) >= 0


def _compare_versions(
    current_version,        # type: str
    required_version,       # type: str
):
    # type: (...) -> int

    if required_version is None and current_version is None:
        return 0

    if required_version is None:
        return -1

    if current_version is None:
        return 1

    current_version_parts = list(map(int, current_version.split(".")))
    required_version_parts = list(map(int, required_version.split(".")))

    max_length = max(len(current_version_parts), len(required_version_parts))
    for i in range(max_length):
        num1 = current_version_parts[i] if i < len(current_version_parts) else 0
        num2 = required_version_parts[i] if i < len(required_version_parts) else 0

        if num1 > num2:
            return 1

        if num2 > num1:
            return -1

    return 0
