import logging
import platform
import sys
import time
import traceback
from datetime import datetime
from pathlib import Path

import serial
import ndef
from src.lib import nfc as nfc
from src.lib.nfc.clf import RemoteTarget

logging.basicConfig(
    format="{asctime}:{name}:{levelname}:{message}",
    datefmt="%Y-%m-%dT%H-%M-%S%z",
    style="{",
    level="INFO",
    handlers=[
        logging.StreamHandler(stream=sys.stderr),
        logging.FileHandler(
            Path("data/logs") / f"{datetime.now().isoformat().replace(':', '_')}.log",
            mode="a",
            encoding="utf-8",
            delay=False,
            **({"errors": "surrogateescape"} if sys.version_info.major >= 3 and sys.version_info.minor >= 10 else {}),
        ),
    ],
    force=True,
    **({"encoding": "utf-8"} if sys.version_info.major >= 3 and sys.version_info.minor >= 10 else {}),
    **({"errors": "surrogateescape"} if sys.version_info.major >= 3 and sys.version_info.minor >= 10 else {}),
)

connected = False
is_win = platform.system().lower() == "windows"

if is_win:
    dev_list = ['com:COM5:pn532']
else:
    dev_list = ['tty:USB0:pn532', 'tty:USB1:pn532', 'tty:USB2:pn532']
while True:
    try:
        if not connected:
            clf = nfc.ContactlessFrontend()
            for dev in dev_list:
                connected = clf.open(dev)
                if connected:
                    print(f"CONNECTED TO {dev}")
                    break
                else:
                    print(f"UNABLE TO CONNECT TO {dev}")

        if connected:
            target = clf.sense(RemoteTarget('106A'), RemoteTarget('106B'), RemoteTarget('212F'))
            if target is not None:
                tag = nfc.tag.activate(clf, target)
                if tag is not None:
                    print(tag)
                    if tag.ndef is not None:
                        if not len(tag.ndef.records):
                            print("EMPTY TAG - WRITING...")
                            if not tag.ndef.is_writeable:
                                print("This Tag is not writeable.")
                                break
                            else:
                                tag.format()
                                #tag.ndef.records = [ndef.TextRecord("Errecinque"),ndef.TextRecord("5812345678")]
                                record=ndef.TextRecord("Errecinque,fixture,5812345678")
                                tag.ndef.records = [record]
                                if tag.ndef.has_changed:
                                    print("WRITE ERROR")
                                else:
                                    print("WRITE OK")

                        for record in tag.ndef.records:
                            print(record)
                    else:
                        print("ERROR NOT NDEF")
            else:
                print("NO TARGET")
        else:
            print("NOT CONNECTED")
    except IOError as io_err:
        print(f"IOError: {io_err}")
        traceback.print_exc()
        connected = False
        clf.close()
    except Exception as e:
        print(f"General Exception: {e}")
        traceback.print_exc()
        connected = False
        clf.close()
    time.sleep(1)

print("EXITING")
clf.close()
