import tempfile
from datetime import datetime
from contextlib import contextmanager
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.run_command import LocalWindowsRunner
from parallels.core.run_command import LocalUnixRunner
from parallels.core.utils import session_dir


class MigratorServer(object):
	"""Class that presents server where the migration tools are running"""
	def __init__(self, config):
		session_dir_path = get_local_session_dir(config)
		if is_run_on_windows():
			self._session_dir = session_dir.WindowsSessionDir(self.runner, session_dir_path)
		else:
			self._session_dir = session_dir.UnixSessionDir(self.runner, session_dir_path)

	def get_session_file_path(self, filename):
		"""Return full path to a temporary file on the server by
		short file name. Function considers session directory settings
		and ensures that session directory exists on the server"""
		return self._session_dir.get_file_path(filename)

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

	def make_session_tmpdir(self, prefix=''):
		"""Create a temporary directory inside session directory."""
		dirname = '_'.join([prefix, datetime.now().strftime('%Y-%m-%d_')])
		return tempfile.mkdtemp(dir=self.session_dir(), prefix=dirname)

	@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 description(self):
		return messages.MIGRATOR_SERVER_DESCRIPTION

	def ips(self):
		return None

	def ip(self):
		return None
