from parallels.core.utils.json_utils import read_json, write_json


class MSSQLServersWithoutPhysicalAccess(object):
    """Persistent storage of list of MSSQL servers for which we don't have physical access

    These are remote MSSQL servers where RPC agent is not installed or is not usable for some reason
    (for example we can't connect to RPC agent because of firewall rule). Usually we can access them
    by MSSQL protocols, but can't execute commands and upload/download files to/from them.
    """
    def __init__(self, filename):
        """Class constructor

        :type filename: str | unicode
        """
        self._filename = filename
        self._servers = None

    def get_servers(self):
        """Get list of servers for which we don't have physical access

        Each item is a tuple with 2 elements - panel server IP and MSSQL server host

        :rtype: list[tuple[str | unicode]]
        """
        if self._servers is None:
            self._servers = read_json(self._filename)
        if self._servers is None:
            self._servers = []

        return self._servers

    def has_server(self, panel_server_ip, mssql_server_host):
        """Check whether MSSQL server is in list of MSSQL servers with no physical access

        :type panel_server_ip: str | unicode
        :type mssql_server_host: str | unicode
        :rtype: bool
        """
        return [panel_server_ip, mssql_server_host] in self.get_servers()

    def write_servers(self, servers):
        """Write list of servers to a file

        :type servers: list[str | unicode]
        """
        self._servers = [list(s) for s in servers]
        write_json(self._filename, servers)
