from parallels.core import safe_format, MigrationNoContextError
from parallels.plesk.source.mail import messages
from parallels.plesk.source.mail.actions.base.mail_migration import MailMigrationAction
from parallels.plesk.source.mail.status_storage import StatusStorage
from parallels.core.utils.migrator_utils import get_option_value_safe


class RetrieveTargetSiteInfo(MailMigrationAction):
    def get_description(self):
        """Get short description of action as string

        :rtype: str | unicode
        """
        return messages.ACTION_RETRIEVE_TARGET_SITE_INFO_DESCRIPTION

    def get_failure_message(self, global_context):
        """Get message for situation when action failed

        :type global_context: parallels.plesk.source.mail.global_context.MailGlobalMigrationContext
        :rtype: str | unicode
        """
        return messages.ACTION_RETRIEVE_TARGET_SITE_INFO_FAILURE

    def run(self, global_context):
        """
        :type global_context: parallels.plesk.source.mail.global_context.MailGlobalMigrationContext
        """
        if get_option_value_safe(global_context.options, 'async_status_report', False):
            global_context.status_storage.set_reporting_mode(StatusStorage.REPORTING_MODE_ASYNC)

        # 1) Get name of target subscription.
        # 2) Check that domain name is subscription or addon domain, but not subdomain
        # (subdomains have no mail service)

        hosting_repo = global_context.hosting_repository

        domain_name = global_context.conn.get_target_domain_name()
        if hosting_repo.subscription.is_exists(domain_name):
            global_context.target_subscription_name = domain_name
        else:
            domain = hosting_repo.domain.get_by_name(domain_name)
            if domain is not None:
                global_context.target_subscription_name = domain.subscription_name
            else:
                subdomain = hosting_repo.subdomain.get_by_name(domain_name)
                if subdomain is not None:
                    raise MigrationNoContextError(safe_format(
                        messages.TARGET_SUBDOMAIN_ERROR, domain_name=domain_name
                    ))
                else:
                    raise MigrationNoContextError(safe_format(
                        messages.NO_DOMAIN_ON_TARGET, domain_name=domain_name
                    ))
