from parallels.core.utils import plesk_utils
from parallels.core.utils.common import cached


class PleskDbCredentialsFetcher(object):
    def __init__(self):
        self._db_credentials_cache = dict()

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

        :rtype : PVPSSubscriptionStorage
        """
        return PleskDbCredentialsFetcher()

    def get(self, plesk_server, db_type, db_params):
        """Get login and password for specified database server

        :type plesk_server: parallels.core.connections.plesk_server.PleskServer
        :type db_type: str | unicode
        :rtype tuple
        """

        cache_key = (plesk_server, db_type, db_params.host)

        login, password = self._db_credentials_cache.get(
            cache_key,
            (None, None)  # default
        )

        if login is None or password is None:
            if plesk_server.is_windows():
                login, password = plesk_utils.get_windows_db_server_credentials(
                    plesk_server, db_type, db_params.host, db_params.port
                )
            else:
                login = db_params.admin
                password = db_params.password
                if login is None or password is None:
                    login, password = plesk_utils.get_unix_db_server_credentials(
                        plesk_server, db_type, db_params.host, db_params.port
                    )

            # put to cache
            cache_value = (login, password)
            self._db_credentials_cache[cache_key] = cache_value

        return login, password