from intelligence.base import *
import requests
import json
import base64


URL = "https://api.metadefender.com/v4"


class MetaDefender(OnlineChecker):

    name = "OPSWAT MetaDefender"
    options = {
        "key": ("", "MetaDefender API key"),
    }
    
    def check(self, analysis):
        detections = { }
        key = self.options.get("key")
        if not key:
            raise KeyError("No API key")
        message = ""
        session = self.preconfigured_session()  # automatically set options such as timeout or ssl_verify
        session.headers.update({'accept': 'application/json'})
        session.headers.update({'apikey': key})

        response = session.get(URL + "/hash/{}".format(analysis.entropy.sha256))
        if response.ok:
            data = response.json()
            if "message" in data:
                raise ValueError(message)
            #print(json.dumps(data, indent=4))
            for avname, res in data.get("scan_results", {}).get("scan_details", {}).items():
                retcode = res.get("scan_result_i", 0)
                # https://onlinehelp.opswat.com/corev3/Description_of_Scan_Results.html
                level = {
                    0: DetectionLevel.CLEAN,
                    1: DetectionLevel.MALWARE,
                    2: DetectionLevel.SUSPECT,
                    4: DetectionLevel.MALWARE,
                    6: DetectionLevel.MALWARE,
                    7: DetectionLevel.CLEAN,
                    8: DetectionLevel.MALWARE,
                    12: DetectionLevel.ENCRYPTED,
                    15: DetectionLevel.ENCRYPTED,

                }.get(retcode, DetectionLevel.UNKNOWN)
                if retcode == 5:
                    signame = "[TIMEOUT]"
                else:
                    signame = res.get("threat_found", "")
                detections[avname] = OnlineDetection(level, signame)
        elif response.status_code == 404:
            return None
        else:
            raise response.raise_for_status()

        url = "https://metadefender.opswat.com/results/file/{}/hash/overview".format(analysis.entropy.sha256)
        return OnlineResult(detections=detections, 
            url=url
        )


