from insights.core.context import HostContext
from insights.core.dr import SkipComponent
from insights.specs import Specs
from insights.core.plugins import datasource
from insights.core.spec_factory import DatasourceProvider
from insights.client.apps.malware_detection import MalwareDetectionClient
from insights.client.config import InsightsConfig


class MalwareDetectionSpecs(Specs):
    @datasource(HostContext)
    def malware_detection_app(broker):
        """
        Custom datasource to collects content for malware scanner if a scanner is present on the system
        """

        try:
            # Only run malware-detection if it was passed as an option to insights-client
            insights_config = InsightsConfig().load_all()
            if not (insights_config and hasattr(insights_config, 'app') and insights_config.app == 'malware-detection'):
                raise SkipComponent
            mdc = MalwareDetectionClient(insights_config)
            scan_results = mdc.run()
            if scan_results:
                return DatasourceProvider(content=scan_results, relative_path="malware-detection-results.json")
            else:
                raise SkipComponent
        except Exception:
            raise SkipComponent
