from parallels.core import messages
from parallels.core.logging import get_logger
from parallels.core.utils.common import is_empty
from parallels.core.utils.migrator_utils import format_owner_login

logger = get_logger(__name__)


def create_panel_user(panel_user, owner, global_context):
    """Create given panel user for given owner in target panel

    :type panel_user: parallels.core.target_data_model.AuxiliaryUser
    :type owner: parallels.core.target_data_model.Client
    :type global_context: parallels.core.global_context.GlobalMigrationContext
    """
    with global_context.safe.try_auxiliary_user(
        format_owner_login(owner.login), panel_user.login,
        messages.ACTION_RESTORE_AUX_USER_CREATE_FAILED.format(panel_user_username=panel_user.login)
    ):
        logger.info(messages.ACTION_RESTORE_AUX_USER_CREATE.format(
            panel_user_username=panel_user.login,
            owner_username=format_owner_login(owner.login)
        ))
        global_context.hosting_repository.panel_user.create(panel_user, owner)


def iter_panel_users_to_create(global_context, subscription_name):
    """
    :type global_context: parallels.core.global_context.GlobalMigrationContext
    :type subscription_name: str | unicode | None
    """
    for owner in global_context.target_model.iter_all_owners():
        for panel_user in owner.auxiliary_users:
            if _is_skip_panel_user(panel_user, owner, global_context, subscription_name):
                continue
            yield panel_user, owner


def _is_skip_panel_user(panel_user, owner, global_context, subscription_name):
    """
    :type panel_user: parallels.core.target_data_model.AuxiliaryUser
    :type global_context: parallels.core.global_context.GlobalMigrationContext
    :type subscription_name: str | unicode
    """
    if panel_user.subscription_name != subscription_name:
        return True

    if panel_user.login == owner.login:
        return True

    if global_context.hosting_repository.panel_user.is_exists(panel_user.login, owner.login):
        logger.debug(messages.ACTION_RESTORE_AUX_USERS_SKIP_EXISTING.format(
            panel_user_username=panel_user.login,
            owner_username=format_owner_login(owner.login)
        ))
        return True

    if is_empty(panel_user.password) and not panel_user.is_active:
        # We do not migrate such users, as we can't create auxiliary users without password.
        # We do not report that to customer to avoid flooding report and log with useless messages:
        # impact is very low - you loose useless auxiliary user (which primary goal is logging in panel)
        # which is not able to login to panel.
        logger.debug(messages.ACTION_RESTORE_AUX_USERS_SKIP_EMPTY_PASSWORD.format(
            panel_user_username=panel_user.login,
            owner_username=format_owner_login(owner.login)
        ))
        return True

    return False
