import re  # noqa: F401
import socket  # noqa: F401
import sys  # noqa: F401

from arq import Retry


async def sent_to_printer(ctx: dict, data: str, address: str, cut_code: str):
    address = "/printer"
    try:
        print("Printing to :", address, "\n", data, "\n")
        with open(address, "w") as printer:
            printer.write(data)
            printer.write("\n")
            print(cut_code)
            printer.write(cut_code)
    except LookupError as e:
        print("Lookup error:", e)
        raise Retry(defer=ctx["job_try"] * 30)
    except FileNotFoundError as e:
        print("File not found error:", e)
        raise Retry(defer=ctx["job_try"] * 30)
    except:  # noqa: E722
        print("Unexpected error:", sys.exc_info()[0])
        # retry the job with increasing back-off
        # delays will be 5s, 10s, 15s, 20s
        # after max_tries (default 5) the job will permanently fail
        raise Retry(defer=ctx["job_try"] * 30)

    # GS = "\x1d"
    # PAPER_CUT = GS + "\x56"
    # # For the printer ESC/POS Reference
    # # https://reference.epson-biz.com/modules/ref_escpos/index.php?content_id=87
    # # The m codes are in decimal and can be converted using the following table
    # # https://www.eso.org/~ndelmott/ascii.html
    # # The \x03 in all the following is to feed 3 lines before cut it can be increased or reduced
    # FUNCTION_B_FULL_CUT = "\x41\x03"
    # FUNCTION_B_PARTIAL_CUT = "\x42\x03"