from parallels.core.logging import get_logger
from parallels.core import messages
from parallels.core.migration_list.factory import create_migration_list_writer
from parallels.core.actions.base.common_action import CommonAction
from parallels.core.actions.migration_list.utils import get_migration_list_file_location
from parallels.core.migration_list.target_data import MigrationListTargetData
from parallels.core.utils.migrator_utils import get_option_value_safe

logger = get_logger(__name__)


class GenerateMigrationList(CommonAction):
    def get_description(self):
        return messages.ACTION_GENERATE_MIGRATION_LIST

    def get_failure_message(self, global_context):
        """
        :type global_context: parallels.core.global_context.GlobalMigrationContext
        """
        return messages.FAILED_GENERATE_MIGRATION_LIST_FILE

    def run(self, global_context):
        """
        :type global_context: parallels.core.global_context.GlobalMigrationContext
        """
        admin_id = global_context.hosting_repository.panel.get_administrator_id(None)

        subscription_names = []
        reseller_logins = []

        for _, source_backup in global_context.migrator.iter_shallow_dumps():
            subscription_names += [s.name for s in source_backup.iter_all_subscriptions()]
            reseller_logins += [
                r.login
                for _, _, r in source_backup.iter_all_subscriptions_with_owner_and_reseller()
                if r is not None
            ]

        logger.info(messages.CHECKING_IF_WEBSPACES_EXIST_IN_TARGET)
        target_subscriptions = global_context.hosting_repository.subscription.get_list(filter_name=subscription_names)
        logger.info(messages.BROWSING_SERVICE_TEMPLATES_WHICH_COULD_USED)
        target_resellers = global_context.hosting_repository.reseller.get_list(reseller_logins)
        target_service_plans = {
            None: [
                st.name for st in global_context.hosting_repository.service_plan.get_list(filter_owner_id=[admin_id])
            ]
        }
        target_addon_service_templates = {
            None: [
                st.name
                for st in global_context.hosting_repository.service_plan_addon.get_list(filter_owner_id=[admin_id])
            ]
        }
        for r in target_resellers:
            target_service_plans[r.username] = [
                st.name for st in global_context.hosting_repository.service_plan.get_list(
                    filter_owner_id=[r.reseller_id]
                )
            ]
            target_addon_service_templates[r.username] = [
                st.name for st in global_context.hosting_repository.service_plan_addon.get_list(
                    filter_owner_id=[r.reseller_id]
                )
            ]

        migration_list_file = get_migration_list_file_location(global_context)
        comment_existing_subscriptions = not get_option_value_safe(
            global_context.options, 'include_existing_subscriptions', default_value=False
        )
        writer = create_migration_list_writer(
            global_context.options.migration_list_format,
            global_context.migrator.get_migration_list_source_data(),
            MigrationListTargetData(global_context.hosting_repository)
        )
        writer.write_initial(
            migration_list_file,
            [existing_subscription.name_canonical for existing_subscription in target_subscriptions],
            target_service_plans,
            target_addon_service_plans=target_addon_service_templates,
            comment_existing_subscriptions=comment_existing_subscriptions
        )

        for subscription_name in subscription_names:
            global_context.subscriptions_status.init_subscription_status(subscription_name)

        logger.info(messages.MIGRATION_LIST_FILE_TEMPLATE_IS_SAVED, migration_list_file)
