# -*- coding: UTF-8 -*-

class CliConnection(object):
    CLI_CAN_NOT_CONNECT_CODE = "1073949185" #与设备通信异常，请检查网络连接或设备状态是否正常
    RE_CONNECTION_TIMES = 3
    _instance = None
    _cli = None

    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super(CliConnection, cls).__new__(cls, *args, **kwargs)
        return cls._instance

    def __init__(self, connectorFactory, ip, sshPort):
        self.connectorFactory = connectorFactory
        self.ip = ip
        self.sshPort = sshPort

    def create(self, user, pawd):
        reConnectionTimes = 0
        while self._cli is None and reConnectionTimes < CliConnection.RE_CONNECTION_TIMES:
            sshConnector = self.connectorFactory.createSshConnector(self.ip, self.sshPort, user, pawd)
            self._cli = sshConnector.getConnectionNoException()
            reConnectionTimes += 1
        del pawd
        return self._cli

    def close(self):
        if self._cli is not None:
            try:
                self._cli.close()
            except:
                return False
            finally:
                self._cli = None
        return True

    def getCli(self, user, pawd):
        try:
            if self._cli is None:
                self.create(user, pawd)
            else:
                cliRet = self._cli.execCmd("show cli configuration")
                #避免CLI超时
                if "-bash:" in cliRet or "Storage:~" in cliRet or "Try 'help'" in cliRet \
                  or "does not exist or has an incorrect format" in cliRet:
                    self._cli = None
                    self.create(user, pawd)
        except:
                #避免CLI超时
                self._cli = None
                self.create(user, pawd)

        if self._cli is None:
            raise Exception(self.CLI_CAN_NOT_CONNECT_CODE, "")

        return self._cli
