from parallels.core.utils.common import cached
from parallels.core.utils.ftp import Ftp


class FTPConnectionPool(object):
    """FTP connection pool - factory for FTP connections to servers"""

    @staticmethod
    @cached
    def get_instance():
        """Single instance for FTPConnectionPool

        :rtype: parallels.core.connections.ftp.connection_pool.FTPConnectionPool
        """
        return FTPConnectionPool()

    def __init__(self):
        self._connections = {}

    def get(self, host, username, password, encoding, ignore_passive_mode_server_ip, ftps_only=True):
        """
        :type host: str | unicode
        :type username: str | unicode
        :type password: str | unicode
        :type encoding: str | unicode
        :type ignore_passive_mode_server_ip: bool
        :type ftps_only: bool
        :rtype: parallels.core.utils.ftp.Ftp
        """
        key = (host, username)

        if key not in self._connections:
            self._connections[key] = Ftp(host, username, password, encoding, ignore_passive_mode_server_ip, ftps_only)

        return self._connections[key]

    def close_all(self):
        for connection in self._connections.values():
            connection.close()
