from parallels.core.logging import get_logger
from parallels.core.actions.base.reseller_action import ResellerAction
from parallels.plesk import messages
from parallels.plesk.actions.hosting_settings.utils import is_copy_external_id_disabled

logger = get_logger(__name__)


class SetResellersExternalId(ResellerAction):
    def get_description(self):
        return messages.ACTION_SET_RESELLERS_EXTERNAL_ID

    def get_failure_message(self, global_context):
        return messages.ACTION_SET_RESELLERS_EXTERNAL_ID_FAILED

    def filter_action(self, global_context):
        return (
                not is_copy_external_id_disabled(global_context)
                and super(SetResellersExternalId, self).filter_action(global_context)
        )

    def is_critical(self):
        return False

    def _get_reseller_failure_message(self, global_context, reseller):
        return messages.ACTION_SET_RESELLERS_EXTERNAL_ID_RESELLER_FAILED.format(
            reseller_username=reseller.login
        )

    def _run_reseller(self, global_context, reseller):
        """Set External ID for given reseller in target panel

        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :type reseller: parallels.core.target_data_model.Reseller
        """
        reseller_dump = self._get_reseller_dump(global_context, reseller)
        if reseller_dump is None:
            logger.error(messages.ACTION_SET_RESELLERS_EXTERNAL_ID_RESELLER_NOT_EXISTS_SOURCE.format(
                reseller_username=reseller.login
            ))
            return

        if reseller_dump.external_id is None:
            logger.debug(messages.ACTION_SET_RESELLERS_EXTERNAL_ID_RESELLER_EMPTY.format(
                reseller_username=reseller.login
            ))
            return

        target_reseller = global_context.hosting_repository.reseller.get_by_username(reseller.login)
        if target_reseller is None:
            logger.warning(messages.ACTION_SET_RESELLERS_EXTERNAL_ID_RESELLER_NOT_EXISTS_TARGET.format(
                reseller_username=reseller.login
            ))
            return

        logger.info(messages.ACTION_SET_RESELLERS_EXTERNAL_ID_RESELLER.format(reseller_username=reseller.login))
        global_context.hosting_repository.reseller.set_external_id(reseller.login, reseller_dump.external_id)

    @staticmethod
    def _get_reseller_dump(global_context, reseller):
        """
        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :type reseller: parallels.core.target_data_model.Reseller
        :rtype: parallels.core.dump.entity.reseller.Reseller | None
        """
        for source in global_context.get_primary_sources_info():
            for reseller_dump in source.load_raw_dump().iter_resellers():
                if reseller.login == reseller_dump.login:
                    return reseller_dump
        return None
