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


URL = "https://www.hybrid-analysis.com/api/v2"

ENVIRONMENTS = {
        100: "Windows 7 32-bits",
        110: "Windows 7 32-bits (with HWP Support)",
        120: "Windows 7 64-bits",
        200: "Android",
        300: "Linux 64-bits environment"
}


class HybridAnalysis(OnlineChecker):

    name = "HybridAnalysis"
    options = {
        "key": ("", "HybridAnalysis 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({'content-type': 'application/json'})
        session.headers.update({'api-key': key})

        finalurl = '/'.join([URL, 'overview', '{}#'.format(analysis.entropy.sha256), 'summary'])
        response = session.get(finalurl)
        if response.ok:
            data = response.json()
            if "message" in data:
                raise ValueError(message)
            threat_score = data.get("threat_score")
            if threat_score is not None:
                level = DetectionLevel.from_number(threat_score)
                name = ", ".join(data.get("tags", []))
            else:
                level = DetectionLevel.UNKNOWN
                name = "(not submitted)"
            detections["Falcon Sandbox"] = OnlineDetection(level, name)
            
            for scanner_data in data.get("scanners", []):
                det = OnlineDetection()
                det.level = DetectionLevel.from_text(scanner_data.get("status", ""))
                percent = scanner_data.get("percent")
                if percent is not None:
                    det.name = "{}% matching".format(percent)
                detections[scanner_data["name"]] = det

        elif response.status_code == 404:
            return None
        else:
            response.raise_for_status()
            return None

        url = "https://www.hybrid-analysis.com/sample/{}/".format(analysis.entropy.sha256)
        return OnlineResult(detections=detections, 
            url=url
        )
