from parallels.core.logging import get_logger
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 DeploySubdomains(SubscriptionAction):
    def get_description(self):
        return messages.ACTION_DEPLOY_SUBDOMAINS

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

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

        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :type subscription: parallels.core.migrated_subscription.MigratedSubscription
        """
        for subdomain_dump in subscription.converted_dump.iter_all_subdomains():
            if global_context.hosting_repository.subdomain.is_exists_by_subscription(
                subscription.name, subdomain_dump.name, subdomain_dump.guid
            ):
                logger.info(messages.ACTION_DEPLOY_SUBDOMAINS_CREATE_SUBDOMAIN_EXISTS.format(
                    subdomain_name=subdomain_dump.name,
                    subdomain_guid=subdomain_dump.guid
                ))
                continue

            logger.info(messages.ACTION_DEPLOY_SUBDOMAINS_CREATE_SUBDOMAIN.format(
                subdomain_name=subdomain_dump.name,
                domain_name=subdomain_dump.parent_domain_name,
                subscription_name=subscription.name
            ))

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

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

            if subdomain_dump.is_forwarding:
                logger.info(messages.ACTION_DEPLOY_SUBDOMAINS_SET_FORWARDING.format(
                    subdomain_name=subdomain_dump.name,
                    subscription_name=subscription.name
                ))
                forwarding_url = subdomain_dump.get_forwarding_url()
                if forwarding_url is None:
                    global_context.safe.fail_subscription(
                        subscription.name,
                        messages.ACTION_DEPLOY_SUBDOMAINS_SET_FORWARDING_ERROR_MISSED_URL.format(
                            subdomain_name=subdomain_dump.name,
                            subscription_name=subscription.name
                        ),
                        is_critical=False
                    )
                try:
                    global_context.hosting_repository.subdomain.set_forwarding(
                        subscription.name, subdomain_dump.name, forwarding_url, subdomain_dump.is_frame_forwarding
                    )
                except Exception as e:
                    logger.exception()
                    # place error into report and proceed to next subdomain
                    global_context.safe.fail_subscription(
                        subscription.name,
                        safe_format(
                            messages.ACTION_DEPLOY_SUBDOMAINS_SET_FORWARDING_ERROR,
                            subdomain_name=subdomain_dump.name,
                            subscription_name=subscription.name,
                            reason=e
                        ),
                        is_critical=False
                    )
                    continue
            elif subdomain_dump.is_virtual_hosting:
                logger.info(messages.ACTION_DEPLOY_SUBDOMAINS_SET_PHYSICAL_HOSTING.format(
                    subdomain_name=subdomain_dump.name,
                    subscription_name=subscription.name
                ))
                try:
                    global_context.hosting_repository.domain.set_physical_hosting(
                        subscription.name, subdomain_dump.name, subdomain_dump.www_root, subdomain_dump.is_enable_ssl
                    )
                except Exception as e:
                    logger.exception()
                    # place error into report and proceed to next subdomain
                    global_context.safe.fail_subscription(
                        subscription.name,
                        safe_format(
                            messages.ACTION_DEPLOY_SUBDOMAINS_SET_PHYSICAL_HOSTING_ERROR,
                            subdomain_name=subdomain_dump.name,
                            subscription_name=subscription.name,
                            reason=e
                        ),
                        is_critical=False
                    )
                    continue
