from contextlib import contextmanager

from parallels.core import safe_format
from parallels.plesk import messages
from parallels.core.connections.target_servers import TargetServer
from parallels.core.runners.windows.agent import WindowsAgentRunner
from parallels.core.utils.session_dir import WindowsSessionDir


class PleskTargetRemoteSmarterMailServer(TargetServer):
    def __init__(self, settings):
        """
        :type settings: parallels.core.migrator_config.PhysicalWindowsServerConfig
        """
        self._settings = settings
        super(PleskTargetRemoteSmarterMailServer, self).__init__()

    def is_windows(self):
        """Check if server is Windows or Linux one

        :rtype: bool
        """
        return True

    @contextmanager
    def runner(self):
        yield WindowsAgentRunner(self._settings, self.description())

    def description(self):
        """Return brief server description which should help end customer
        to identify server and which should be used in all messages

        :rtype: str | unicode
        """
        return safe_format(messages.TARGET_REMOTE_SMARTER_MAIL_DESCRIPTION, ip=self.ip())

    def ip(self):
        """Return main IP address of the server

        :rtype: str | unicode
        """
        return self._settings.ip

    def _create_session_dir(self):
        """Create session directory object

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

    def __hash__(self):
        return hash(self.ip())

    def __eq__(self, another):
        return isinstance(another, PleskTargetRemoteSmarterMailServer) and another.ip() == self.ip()