import json

import pyscripts

from msgbus import (
    FM_PARAM,
    TK_SYS_ACK,
    TK_PRN_GETSTATUS,
)
from sysactions import (
    action,
    get_model,
    get_cfg,
    print_report,
    get_poslist,
)
from bustoken import TK_PROD_GET_PRINTERS_INFO

from utilfunctions import get_device_service

mb_context = pyscripts.mbcontext


@action
def get_printer_status(pos_id):
    printer_info_list = []

    printer_ok_message = "OK"
    printer_not_ok_message = "Falha"

    msg = mb_context.MB_EasySendMessage("ProductionSystem", TK_PROD_GET_PRINTERS_INFO, FM_PARAM, None)

    if msg.token == TK_SYS_ACK:
        printers = json.loads(msg.data)
        for printer in printers:
            printer_info = [printer]
            try:
                msg = mb_context.MB_EasySendMessage(printer, TK_PRN_GETSTATUS, FM_PARAM, None)

                if msg.data == "0":
                    printer_info.append(printer_ok_message)
                else:
                    printer_info.append(printer_not_ok_message)
            except Exception as _:
                printer_info.append(printer_not_ok_message)
            printer_info_list.append(printer_info)

    pos_list = get_poslist()
    for pos in sorted(pos_list):
        printer_info = ["POS {}".format(str(pos).zfill(2))] if pos != 0 else ["Delivery"]
        try:
            model = get_model(pos)
            pod_function = get_cfg(pos).key_value('pod')
            if pod_function in ("OT", "DL"):
                continue

            printer = get_device_service(
                pos_id=pos_id,
                device_type="printer",
            )
            msg = mb_context.MB_EasySendMessage(printer, TK_PRN_GETSTATUS, FM_PARAM, None)

            if msg.data == "0":
                printer_info.append(printer_ok_message)
            else:
                printer_info.append(printer_not_ok_message)
        except Exception as _:
            printer_info.append(printer_not_ok_message)
        printer_info_list.append(printer_info)

    model = get_model(pos_id)
    print_report(pos_id, model, True, "printer_report", pos_id, printer_info_list)
