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 DeployDomains(SubscriptionAction):
    def get_description(self):
        return messages.ACTION_DEPLOY_DOMAINS

    def get_failure_message(self, global_context, subscription):
        return messages.ACTION_DEPLOY_DOMAINS_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_addon_domains())

    def run(self, global_context, subscription):
        """Perform creation of add-on domains for given subscription on target Plesk

        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :type subscription: parallels.core.migrated_subscription.MigratedSubscription
        """

        for domain_dump in subscription.converted_dump.iter_addon_domains():
            if global_context.hosting_repository.domain.is_exists_by_subscription(
                subscription.name, domain_dump.name, domain_dump.guid
            ):
                logger.info(messages.ACTION_DEPLOY_DOMAINS_CREATE_DOMAIN_EXISTS.format(
                    domain_name=domain_dump.name,
                    domain_guid=domain_dump.guid
                ))
                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_dump.name)

            logger.info(messages.ACTION_DEPLOY_DOMAINS_CREATE_DOMAIN.format(
                domain_name=domain_dump.name,
                subscription_name=subscription.name
            ))

            # invalidate cache associated with this domain
            global_context.cache_state_controllers.domain.invalidate_cache_states(domain_dump.name)

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

            if domain_dump.is_forwarding:
                logger.info(messages.ACTION_DEPLOY_DOMAINS_SET_FORWARDING.format(
                    domain_name=domain_dump.name,
                    subscription_name=subscription.name
                ))
                forwarding_url = domain_dump.get_forwarding_url()
                if forwarding_url is None:
                    global_context.safe.fail_subscription(
                        subscription.name,
                        messages.ACTION_DEPLOY_DOMAINS_SET_FORWARDING_ERROR_MISSED_URL.format(
                            domain_name=domain_dump.name,
                            subscription_name=subscription.name
                        ),
                        is_critical=False
                    )
                try:
                    global_context.hosting_repository.domain.set_forwarding(
                        subscription.name, domain_dump.name, forwarding_url, domain_dump.is_frame_forwarding
                    )
                except Exception as e:
                    logger.exception()
                    # place error into report and proceed to next domain
                    global_context.safe.fail_subscription(
                        subscription.name,
                        safe_format(
                            messages.ACTION_DEPLOY_DOMAINS_SET_FORWARDING_ERROR,
                            domain_name=domain_dump.name,
                            subscription_name=subscription.name,
                            reason=e
                        ),
                        is_critical=False
                    )
                    continue
            elif domain_dump.is_virtual_hosting:
                logger.info(messages.ACTION_DEPLOY_DOMAINS_SET_PHYSICAL_HOSTING.format(
                    domain_name=domain_dump.name,
                    subscription_name=subscription.name
                ))
                try:
                    global_context.hosting_repository.domain.set_physical_hosting(
                        subscription.name, domain_dump.name, domain_dump.www_root, domain_dump.is_enable_ssl
                    )
                except Exception as e:
                    logger.exception()
                    # place error into report and proceed to next domain
                    global_context.safe.fail_subscription(
                        subscription.name,
                        safe_format(
                            messages.ACTION_DEPLOY_DOMAINS_SET_PHYSICAL_HOSTING_ERROR,
                            domain_name=domain_dump.name,
                            subscription_name=subscription.name,
                            reason=e
                        ),
                        is_critical=False
                    )
                    continue

