from functools import wraps

from parallels.core.logging import get_logger
from parallels.core.registry import Registry
from parallels.core.reports.model.issue import Issue
from parallels.core.utils.common import safe_format
from parallels.plesk.source.plesk import messages

logger = get_logger(__name__)


def entity_data_dump(description, default=None):
    """The decorator for the methods of
    parallels.plesk.source.plesk.hosting_description.provider.plesk.PleskHostingDescriptionProvider

    :type description: str | unicode
    :type default:
    """
    def entity_settings_decorator(func):
        @wraps(func)
        def func_wrapper(*args, **kwargs):
            try:
                return func(*args, **kwargs)
            except Exception as e:
                logger.exception()
                entity_path = ''
                # args[0] is the self argument of the decorated methods of
                # parallels.plesk.source.plesk.hosting_description.provider.plesk.PleskHostingDescriptionProvider
                current_entities = getattr(args[0], '_current_entities') if args else None
                if current_entities:
                    entity_path = '/'.join([
                        '%s (%s)' % (entity_type, entity_name)
                        for entity_type, entity_name in current_entities
                    ])
                Registry.get_instance().get_context().pre_check_report.add_issue(
                    'dump_data',
                    Issue.SEVERITY_WARNING,
                    safe_format(
                        messages.FAILED_TO_DUMP_ENTITY_DATA,
                        entity_path=entity_path,
                        description=description,
                        error=e,
                    )
                )
                return default
        return func_wrapper
    return entity_settings_decorator
