import time

import threaded_sender
from telnet_connection import TelnetConnection

class Sender(threaded_sender.Sender):

    CONNECTION_CLASS = TelnetConnection
    OK_TIMEOUT = 20

    def _connect(self):
        if self.connection:
            self.connection.close()
        self.connection = self.CONNECTION_CLASS(self.usb_info['IP'],\
                                                self.profile.get('port', 23),\
                                                self.profile.get("timeout", None))
        if not self.connection:
            raise RuntimeError("No connection to host:%s" % self.usb_info['IP'])
        attempts_left = 2
        while attempts_left:
            self.connection.send(b"\nM105\n", raw=True)
            answer = self.connection.recv()
            if answer and self.OK in answer:
                while self.connection.recv():
                    pass # read all of the possible junk
                return True
            attempts_left -= 1
            time.sleep(1)

    def close(self):
        try:
            self.connection.reset()
        except:
            pass
        super().close()
