import logging
import os
import serial

import config
import platforms
from base_detector import BaseDetector


class GPIOUARTDetector(BaseDetector):

    PORT_PATH_BASE = "/dev/tty"

    def __init__(self, app):
        self.app = app
        self.printerid_dict_template = {'VID': 'UART', 'PID': '0PIN'}
        self.logger = logging.getLogger(self.__class__.__name__)

    def get_printers_list(self):
        # this is a one shot detector, that will be updated only ones per run of application
        port_paths = config.get_settings()['gpio_uart']['ports']
        use_with_gpio_interface_buttons = config.get_settings()['gpio_uart']['allow_use_with_buttons']
        printers = []
        if (not self.app.gpio_interface or use_with_gpio_interface_buttons) and platforms.PLATFORM == "rpi":
            for port_path in port_paths:
                if os.path.exists(port_path):
                    printerid_dict = {}
                    printerid_dict.update(self.printerid_dict_template)
                    printerid_dict['SNR'] = port_path.replace(self.PORT_PATH_BASE, "")
                    printerid_dict['COM'] = port_path
                    if printerid_dict not in printers:
                        printers.append(printerid_dict)
        return printers


if __name__ == "__main__":
    import _fake_parent
    app = _fake_parent.FakeParent.FakeApp()
    app.gpio_interface = True
    ud = GPIOUARTDetector(app)
    print(ud.get_printers_list())
    app.gpio_interface = False
    ud = GPIOUARTDetector(app)
    print(ud.get_printers_list())
