import os.path
import tempfile
from datetime import datetime
from contextlib import contextmanager

from parallels.utils import is_run_on_windows
from parallels.common.registry import Registry
from parallels.common.utils.config_utils import ConfigSection
from parallels.common.run_command import LocalWindowsRunner
from parallels.common.run_command import LocalUnixRunner
from parallels.common.utils import session_dir


class MigratorServer(object):
	"""Class that presents server where the migration tools are running"""
	def __init__(self, config):
		global_section = ConfigSection(config, 'GLOBAL')
		session_dir_suffix = global_section.get('session-dir', 'migration-session')
		session_dir_path = os.path.join(Registry.get_instance().get_base_dir(), 'sessions', session_dir_suffix)
		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 "this server"

	def ips(self):
		return None

	def ip(self):
		return None
