from intelligence.base import *
import requests
import json

URL = "https://opentip.kaspersky.com/api/v1/"



class KasperskyOpenThreatIntelligencePortal(OnlineChecker):

    name = "Kaspersky OpenTIP"
    options = {
        "key": ("", "Kaspersky OpenTIP API key"),
    }
    
    def check(self, analysis):
        detections = { }
        key = self.options.get("key")
        if not key:
            raise KeyError("No API key")
        url = "https://opentip.kaspersky.com/{}/results".format(analysis.entropy.sha256)
        session = self.preconfigured_session()  # automatically set options such as timeout or ssl_verify
        session.headers.update({
            "x-api-key": key,
            "accept": "application/json",
        })

        # search
        response = session.get(f"{URL}search/hash?request={analysis.entropy.sha256}")
        if response.ok:
            data = response.json()
            if not data:
                return None
            det = OnlineDetection()
            analysis_name = analysis.entropy.md5
            if "FileGeneralInfo" in data:
                det.level = DetectionLevel.from_text(data["FileGeneralInfo"].get("FileStatus", ""))
                if "HitsCount" in data["FileGeneralInfo"]:
                    analysis_name = "Seen {} times".format(data["FileGeneralInfo"].get("HitsCount", 0))
            if "DetectionsInfo" in data and data["DetectionsInfo"]:
                det.name = data["DetectionsInfo"][0].get("DetectionName", "")
            detections[analysis_name] = det

        elif response.status_code == 404:
            return None
        else:
            response.raise_for_status()
            return None
        return OnlineResult(detections=detections, 
            url=url
        )
