from parallels.core.utils.common import open_no_inherit
from parallels.core.utils.restore_hosting_utils import restore_hosting_settings_lock
from parallels.core.utils.windows_utils import path_join as windows_path_join
from parallels.core.utils import vdir_utils
from parallels.core.utils import plesk_utils
from parallels.core.utils.windows_utils import convert_path
from threading import Lock


class PathConverter(object):
    @staticmethod
    def convert(subscription, site, path):
        source_vhost_path = windows_path_join(
            subscription.web_source_server.vhosts_dir,
            subscription.name_idn
        )
        return convert_path(subscription, path, source_vhost_path)


def get_vdirs_dict(global_context, subscription, site):
    """Get list of virtual directories of a site

    Returns: dictionary, key is virtual directory name, value is target path

    Note that function relies on transfer virtual directories action, which should write
    converted virtual directory XML to a file in session directory

    :type global_context: parallels.core.global_context.GlobalMigrationContext
    :type subscription: parallels.core.migrated_subscription.MigratedSubscription
    :rtype: dict[str | unicode, str | unicode]
    """
    vdir_info_source = _load_vdirs_xml(global_context, site).decode('utf-8')
    vdirs_dict_source = vdir_utils.get_vdir_to_path(vdir_info_source)
    with restore_hosting_settings_lock:
        vdir_info_target = plesk_utils.get_vdir_info(subscription.web_target_server, site.name)
    vdirs_dict_target = vdir_utils.get_vdir_to_path(vdir_info_target)

    result = {}
    for vdir_name, path in vdirs_dict_target.items():
        if vdir_name in vdirs_dict_source:
            result[vdir_name] = path

    return result


def _load_vdirs_xml(global_context, site):
    filename = global_context.session_files.get_converted_vdir_xml(
        site.name
    )
    with open_no_inherit(filename, 'rb') as f:
        return f.read()


source_websrvmng_lock = Lock()