from insights.core.context import HostContext
from insights.core.exceptions import SkipComponent
from insights.core.plugins import datasource
from insights.core.spec_factory import DatasourceProvider
from insights.client import auto_config
from insights.client.apps.malware_detection import MalwareDetectionClient
from insights.client.config import InsightsConfig
from insights.specs import Specs
import logging
logger = logging.getLogger(__name__)


class MalwareDetectionSpecs(Specs):
    # timeout=0 disables the datasource timeout alarm, allowing malware-detection to run for as long as necessary
    @datasource(HostContext, timeout=0)
    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()
            auto_config.try_auto_configuration(insights_config)
            if not (insights_config and hasattr(insights_config, 'app') and insights_config.app == 'malware-detection'):
                raise SkipComponent("Only run malware-detection app when specifically requested via --collector option")
            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("No scan results were produced")
        except SkipComponent as msg:
            raise SkipComponent("Skipping malware-detection app: {0}".format(str(msg)))
        except Exception as err:
            from traceback import format_exc
            err_msg = "Unexpected exception in malware-detection app: {0}".format(str(err))
            logger.error(err_msg)
            logger.debug(format_exc())
            raise SkipComponent(err_msg)
