from intelligence.base import *
import requests
import json

URL = "https://virus.exchange/api/"



class VirusExchange(OnlineChecker):

    name = "VirusExchange"
    options = {
        "key": ("", "VirusExchange API key"),
    }

    def __session(self):
        session = self.preconfigured_session()  # automatically set options such as timeout or ssl_verify
        session.headers.update({'accept': 'application/json'})
        key = self.options.get("key")
        if not key:
            raise KeyError("No API key")
        session.headers.update({'Authorization': f"Bearer {self.options['key']}"})
        return session

    def check(self, analysis):
        session = self.__session()
        response = session.get(f"{URL}samples/{analysis.entropy.sha256.lower()}")
        if not response.ok:
            if response.status_code == 404:
                return None
            raise response.raise_for_status()
        data = response.json()
        #print(json.dumps(data, indent=4))
        if not "first_seen" in data:
            return None
        det = OnlineDetection()
        for tag in data.get("tags", []):
            lvl = DetectionLevel.from_text(tag)
            if lvl != DetectionLevel.UNKNOWN:
                det.level = lvl
                break
        det.name = f"First seen on {data['first_seen']}"
        if data.get("names", []):
            entry = data["names"][0]
        else:
            entry = "???"
        return OnlineResult(
                detections= { entry : det }, 
                url=""
        )

  
    def download(self, query):
        if len(query) != 64:
            return None
        session = self.__session()
        response = session.get(f"{URL}samples/{query}")
        if not response.ok:
            if response.status_code == 404:
                return None
            raise response.raise_for_status()
        dl = response.json().get("download_link")
        if not dl:
            return None
        content = session.get(dl).content
        return OnlineFile(
            url=dl, 
            content=content
        )
