import time
import config

import formlabs_sender

class Checker:

    PORT = 35

    def __init__(self, parent_scanner=None, profile=None):
        self.parent_scanner = parent_scanner
        self.logger = parent_scanner.logger
        self.profile = profile

    def check(self, printer, existing_profile=None):
        #TODO implement existing_profile comparison
        try:
            ip = printer.get('IP')
            sender = formlabs_sender.Sender(None, usb_info={"IP": ip, "RUNONCE": True}, profile={})
            sender._connect()
        except RuntimeError:
            self.logger.warning("Unable to connect to FormLabs printer")
        else:
            if sender.is_operational():
                for profile in self.parent_scanner.profiles:
                    machine_type_id = profile.get('network_detect', {}).get('machine_type_id')
                    if machine_type_id and machine_type_id in sender.machine_type_id:
                        vid, pid = profile.get('vids_pids')[0]
                        printer = {"IP": ip, "PORT": self.PORT, "SNR": sender.serial_number, "VID": vid, "PID": pid}
                        break
                else:
                    self.logger.warning("Detected unsupported FormLabs printer. Save info/status response to logs")
                    info = sender._get_printer_info_tcp()
                    status = sender._get_printer_status_tcp()
                    self.logger.info('Unknown object info:' + str(info))
                    self.logger.info('Unknown object status:' + str(status))
            # disconnecting from printer
        finally:
            try:
                sender._close_tcp_client()
            except:
                pass
        return printer
