from contextlib import contextmanager

from parallels.core import messages
from parallels.core.utils.common import cached
from parallels.core.utils.session_dir import WindowsSessionDir


class MSSQLRemoteServer(object):
    """Physical server which contains MSSQL server connected to panel as remote MSSQL server"""

    def __init__(self, host, panel_server):
        self._host = host
        self._panel_server = panel_server

    @contextmanager
    def runner(self):
        with self._panel_server.proxy_runner(self._host) as runner:
            yield runner

    def is_windows(self):
        """Check whether this server is Windows or Unix

        :rtype: bool
        """
        return True

    @cached
    def ip(self):
        """IP address of a server (one, any of multiple)

        :rtype: str
        """
        with self._panel_server.runner() as runner:
            return runner.resolve(self._host)

    def description(self):
        """Description of a server, to be used in messages

        :rtype: unicode
        """
        return messages.PHYSICAL_SERVER_DESCRIPTION % self._host

    def get_session_file_path(self, filename):
        """Get path to a file inside migrator's session directory

        :type filename: str | unicode
        :rtype: str | unicode
        """
        return self.session_dir.get_file_path(filename)

    def get_session_dir_path(self):
        """Get path to migrator's session directory on that server

        :rtype: str | unicode
        """
        return self.session_dir.get_session_dir_path()

    @property
    @cached
    def session_dir(self):
        """Get session directory object

        :rtype: parallels.core.utils.session_dir.SessionDir
        """
        return WindowsSessionDir(self.runner, self._panel_server.settings().remote_mssql_session_dir)
