import ntpath
import os
import posixpath

import parallels
from parallels.core.runners.unix.local import LocalUnixRunner
from parallels.core.runners.utils import transfer_local_dir
from parallels.core.runners.windows.local import LocalWindowsRunner
from parallels.core.utils.common.threading_utils import execute_once_synchronized_by_args
from parallels.core.utils.migrator_utils import get_package_extras_file_path


def get_local_mail_migrator_executable(is_windows):
    """
    :type is_windows: bool
    :rtype: str | unicode
    """
    directory = _get_local_mail_migrator_directory(is_windows)
    executable = _get_local_mail_migrator_executable_name(is_windows)
    return os.path.join(directory, executable)


@execute_once_synchronized_by_args
def get_mail_migrator_executable(server):
    """Get mail migrator executable location on the server. Deploy mail migrator to the server if necessary.

    :type server: parallels.core.connections.server.Server
    :rtype: str | unicode
    """
    is_windows = server.is_windows()

    with server.runner() as runner:
        if isinstance(runner, LocalUnixRunner) or isinstance(runner, LocalWindowsRunner):
            return get_local_mail_migrator_executable(is_windows=is_windows)
        else:
            remote_dir = server.get_session_dir_path()
            transfer_local_dir(
                local_dir=_get_local_mail_migrator_directory(is_windows),
                remote_dir=remote_dir,
                runner=runner,
                is_windows=is_windows
            )
            return (ntpath if is_windows else posixpath).join(
                remote_dir, _get_local_mail_migrator_executable_name(is_windows)
            )


def _get_local_mail_migrator_directory(is_windows):
    """
    :type is_windows: bool
    :rtype: str | unicode
    """
    mail_migrator_path = get_package_extras_file_path(parallels.core, "mail-migrator")
    if is_windows:
        return os.path.join(mail_migrator_path, 'windows')
    else:
        return os.path.join(mail_migrator_path, 'linux')


def _get_local_mail_migrator_executable_name(is_windows):
    """
    :type is_windows: bool
    :rtype: str | unicode
    """
    if is_windows:
        return 'MailMigrator.exe'
    else:
        return 'mail-migrator'
