from parallels.core.logging import get_logger
from parallels.core.actions.deploy.utils import remove_coinciding_dns_records
from parallels.core.utils.common import is_empty_iterator, safe_format
from parallels.plesk import messages
from parallels.core.actions.base.subscription_action import SubscriptionAction

logger = get_logger(__name__)


class DeployDomainAliases(SubscriptionAction):
    def get_description(self):
        return messages.ACTION_DEPLOY_DOMAIN_ALIASES

    def get_failure_message(self, global_context, subscription):
        return messages.ACTION_DEPLOY_DOMAIN_ALIASES_FAILED.format(subscription_name=subscription.name)

    def is_critical(self):
        return False

    def filter_subscription(self, global_context, subscription):
        return not is_empty_iterator(subscription.converted_dump.iter_aliases())

    def run(self, global_context, subscription):
        """Perform creation of domain aliases for given subscription on target Plesk

        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :type subscription: parallels.core.migrated_subscription.MigratedSubscription
        """
        for domain_alias_dump in subscription.converted_dump.iter_aliases():
            if global_context.hosting_repository.domain_alias.is_exists_by_subscription(subscription.name, domain_alias_dump.name):
                logger.info(messages.ACTION_DEPLOY_DOMAIN_ALIASES_CREATE_DOMAIN_ALIAS_EXISTS.format(
                    domain_alias_name=domain_alias_dump.name
                ))
                continue

            if global_context.target_panel_obj.is_remove_coinciding_dns_records():
                # if target panel is unable to create add-on domain which name matching one of existing
                # DNS records, remove such DNS records first
                remove_coinciding_dns_records(global_context, subscription, domain_alias_dump.name)

            logger.info(messages.ACTION_DEPLOY_DOMAIN_ALIASES_CREATE_DOMAIN_ALIAS.format(
                domain_alias_name=domain_alias_dump.name,
                subscription_name=subscription.name
            ))

            try:
                global_context.hosting_repository.domain_alias.create_from_dump(
                    subscription.name,
                    domain_alias_dump,
                    domain_alias_dump.parent_domain_name
                )
            except Exception as e:
                logger.exception()
                # place error into report and proceed to next domain alias
                global_context.safe.fail_subscription(
                    subscription.name,
                    safe_format(
                        messages.ACTION_DEPLOY_DOMAIN_ALIASES_CREATE_DOMAIN_ALIAS_ERROR,
                        domain_alias_name=domain_alias_dump.name,
                        domain_name=domain_alias_dump.parent_domain_name,
                        subscription_name=subscription.name,
                        reason=e
                    ),
                    is_critical=False
                )
                continue
