from contextlib import contextmanager

from parallels.core.connections.server import Server
from parallels.core.migrator_config import get_local_session_dir
from parallels.core import messages
from parallels.core.utils.common import is_run_on_windows
from parallels.core.runners.windows.local import LocalWindowsRunner
from parallels.core.runners.unix.local import LocalUnixRunner
from parallels.core.utils import session_dir


class MigratorServer(Server):
    """Class that presents server where the migration tools are running"""
    def __init__(self, config):
        self._config = config
        super(MigratorServer, self).__init__()

    @property
    def session_dir(self):
        """Migration session storage directory

        :rtype: parallels.core.utils.session_dir.UnixSessionDir | parallels.core.utils.session_dir.WindowsSessionDir
        """
        return self._session_dir

    def get_session_file_path(self, *args):
        """Return full path to a file in the session directory on the server by given parts of related path;
        considers session directory settings and ensures that session directory and parent directory exists

        :rtype: str
        """
        return self._session_dir.get_file_path(*args)

    def get_session_dir_path(self):
        """Return path to session directory - directory where 
        we should store all temporary files"""
        return self._session_dir.get_session_dir_path()

    @contextmanager
    def runner(self):
        """Get runner object to execute commands on the server"""
        if is_run_on_windows():
            yield LocalWindowsRunner.get_instance()
        else:
            yield LocalUnixRunner()

    def is_local(self):
        return True

    def is_windows(self):
        return is_run_on_windows()

    def description(self):
        return messages.MIGRATOR_SERVER_DESCRIPTION

    def ips(self):
        return None

    def ip(self):
        return None

    def _create_session_dir(self):
        if self._config is None:
            return None
        session_dir_path = get_local_session_dir(self._config)
        if is_run_on_windows():
            return session_dir.WindowsSessionDir(self.runner, session_dir_path)
        else:
            return session_dir.UnixSessionDir(self.runner, session_dir_path, secure_subdir=False)
