import os

from parallels.core.connections.source_server import SourceServer
from parallels.core.panels import get_additional_source_panel, AdditionalSourcePanelConfig
from parallels.core.registry import Registry
from parallels.core.utils.migrator_utils import get_optional_option_value


class ConfigFilter(object):
    NEED_GENERATE_HD = 'need-generate-hd'
    NEED_DEPLOY_AGENT = 'need-deploy-agent'
    NEED_DEPLOY_PYTHON = 'need-deploy-python'
    HD_GENERATION_CAN_BE_SKIPPED = 'hd-generation-can-be-skipped'


def get_configs(global_context, config_filter=None):
    """Returns list of hosting description configs which satisfy filter requirements

    :type config_filter: str | None
    :type global_context: parallels.core.global_context.GlobalMigrationContext
    :rtype: list [parallels.plesk.hosting_description.config.HostingDescriptionConfig]
    """
    source_panel = get_additional_source_panel(global_context)
    if source_panel is None:
        return []

    if (
            config_filter == ConfigFilter.NEED_DEPLOY_PYTHON
            and source_panel.execution != AdditionalSourcePanelConfig.EXTENSION_ENTRY_POINT_MIGRATOR_PYTHON
    ):
        return []

    configs = []

    for config in global_context.conn.iter_hosting_description_configs():
        source_server = global_context.conn.get_source_by_id(config.source_id)
        if not isinstance(source_server, SourceServer):
            continue

        # cached hd exists
        if os.path.isfile(config.path):
            if (
                    (
                            config_filter == ConfigFilter.NEED_GENERATE_HD
                            or config_filter == ConfigFilter.NEED_DEPLOY_AGENT
                            or config_filter == ConfigFilter.NEED_DEPLOY_PYTHON
                    )
                    and not get_optional_option_value(global_context.options, 'reload_source_data', False)
                    and Registry.get_instance().get_command_name() != 'deploy-agent'
            ):
                continue
        # no cached hd
        else:
            if config_filter == ConfigFilter.HD_GENERATION_CAN_BE_SKIPPED:
                continue

        configs.append(config)

    return configs


def configs_with_source_server_exist(global_context):
    """Returns true if at least one config with source server found

    :type global_context: parallels.core.global_context.GlobalMigrationContext
    :rtype: bool
    """
    for config in global_context.conn.iter_hosting_description_configs():
        source_server = global_context.conn.get_source_by_id(config.source_id)
        if isinstance(source_server, SourceServer):
            return True
