import logging
import time
import json
from threading import Thread

from bustoken import TK_POS_UPDATER_GET_VERSIONS
from msgbus import TK_SYS_ACK
from sysactions import action, send_message

last_pos_version = ""
pos_version_thread = None

logger = logging.getLogger("PosActions")


@action
def get_pos_versions(_):
    global pos_version_thread

    if pos_version_thread is None:
        pos_version_thread = Thread(target=_get_pos_version)
        pos_version_thread.daemon = True
        pos_version_thread.start()

    return last_pos_version


def _get_pos_version():
    global last_pos_version

    while True:
        try:
            reply = send_message("PosUpdater", TK_POS_UPDATER_GET_VERSIONS, timeout=5000000)
            if reply.token == TK_SYS_ACK:
                last_pos_version = reply.data
        except Exception as _:
            logger.exception("Error getting POS Versions")
        finally:
            time.sleep(5)
