from intelligence.base import *
import requests
import json

URL = "https://virusshare.com/apiv2"


class VirusShare(OnlineChecker):

    name = "VirusShare"
    options = {
        "key": ("", "VirusShare API key"),
    }
    
    def check(self, analysis):
        key = self.options.get("key")
        if not key:
            raise KeyError("No API key")
       
        session = self.preconfigured_session()  # automatically set options such as timeout or ssl_verify
        response = session.get(f"{URL}/file?apikey={key}&hash={analysis.entropy.sha256}")
        if response.ok:
            data = response.json()
            response = data.get("response", 0)
            if response == 0:
                return None
            date_found = data.get("added_timestamp", "")
            md5 = data.get("md5", "")
            level = {
                1: DetectionLevel.MALWARE,
                2: DetectionLevel.CLEAN,
            }.get(response)
            
            return OnlineResult(detections={
                    md5: OnlineDetection(level, f"Added on {date_found}")
                }, 
                url=f"https://virusshare.com/file?{analysis.entropy.sha256}"
            )
        elif response.status_code == 404:
            return None
        else:
            raise response.raise_for_status()

    def download(self, query):
        key = self.options.get("key")
        if not key:
            raise KeyError("No API key")
       
        session = self.preconfigured_session()  # automatically set options such as timeout or ssl_verify
        response = session.get(f"{URL}/download?apikey={key}&hash={query}")
        if response.ok:
            return OnlineFile(
                url=f"https://virusshare.com/file?{query}",
                content=response.content
            )
        elif response.status_code == 404:
            return None
        else:
            raise response.raise_for_status()
