from parallels.core.logging import get_logger
from parallels.core import messages
from parallels.core.actions.base.common_action import CommonAction
from parallels.core.actions.utils.logging_properties import LoggingProperties
from parallels.core.reports.model.report import Report
from parallels.core.reports.printer import print_report
from parallels.core.safe import add_report_issues
from parallels.core.utils.common import is_empty_iterator

logger = get_logger(__name__)


class DeployResellersPrintReport(CommonAction):
    def get_description(self):
        return messages.ACTION_DEPLOY_RESELLERS_PRINT_SUMMATY

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

    def get_logging_properties(self):
        return LoggingProperties(info_log=False)

    def is_critical(self):
        return False

    def filter_action(self, global_context):
        return not is_empty_iterator(global_context.target_model.resellers)

    def run(self, global_context):
        failed_resellers = global_context.safe.failed_objects.resellers
        resellers_count = 0
        failed_resellers_count = 0
        report = Report(messages.DETAILED_RESELLER_MIGRATION_STATUS, None)
        for reseller in global_context.target_model.resellers.values():
            if reseller.login in global_context.target_existing_objects.resellers:
                # exclude existing resellers from report
                continue
            resellers_count += 1
            reseller_report = report.subtarget(
                messages.DETAILED_RESELLER_MIGRATION_STATUS_TARGET_RESELLER,
                reseller.login
            )

            if reseller.login in failed_resellers:
                add_report_issues(reseller_report, failed_resellers[reseller.login])
                failed_resellers_count += 1

        print_report(report, 'resellers_report_tree', show_no_issue_branches=False)

        logger.info(messages.SUMMARY)
        logger.info(
            messages.OPERATION_FINISHED_SUCCESSFULLY_FOR_RESELLERS,
            resellers_count - failed_resellers_count,
            resellers_count
        )
