import printerconstants
import printer_text_formatter
from xml.etree import cElementTree as eTree
from typing import Optional


import sysactions

REPRINT_CONSTANT = "####REPRINT_TEXT####"


def parse_constants(
    printer_text,       # type: str
    pos_id=None,        # type: Optional[eTree.XML]
    is_reprint=False,   # type: Optional[bool]
):
    # type: (...) -> str

    if not is_reprint:
        return printer_text.replace(REPRINT_CONSTANT, "")

    model = sysactions.get_model(posid=pos_id)
    reprint_text = _get_reprint_text(model=model)
    return printer_text.replace(REPRINT_CONSTANT, reprint_text)


def _get_reprint_text(
    model,  # type: eTree.XML
):
    # type: (...) -> str

    reprint_text = rollback_printer_default_font()

    if model is not None:
        reprint_translation = sysactions.translate_message(
            model=model,
            message_key="REPRINT_TEXT_MESSAGE",
        )
    else:
        reprint_translation = "****REIMPRESSAO****"

    reprint_text += printerconstants.TXT_BOLD_ON
    reprint_text += printerconstants.TXT_2HEIGHT
    reprint_text += printerconstants.TXT_2WIDTH
    reprint_text += printer_text_formatter.center_text(
        text=reprint_translation,
        line_size=printerconstants.COLS/2,
    )

    reprint_text += rollback_printer_default_font()

    return reprint_text


def rollback_printer_default_font():
    # type: () -> str

    return "{}{}{}{}{}".format(
        printerconstants.TXT_NORMAL,
        printerconstants.TXT_BOLD_OFF,
        printerconstants.TXT_FONT_A,
        printerconstants.TXT_ALIGN_LT,
        printerconstants.TXT_INVERT_OFF
    )
