from intelligence.base import *
import requests
import json


URL = "https://analyze.intezer.com/api/v2-0"



class Intezer(OnlineChecker):

    name = "Intezer"
    options = {
        "key": ("", "Intezer API key"),
    }
    
    def check(self, analysis):
        detections = { }
        key = self.options.get("key")
        if not key:
            raise KeyError("No API key")

        # login
        session = self.preconfigured_session()  # automatically set options such as timeout or ssl_verify
        response = session.post(URL + '/get-access-token', json={'api_key': key})
        response.raise_for_status()
        session.headers['Authorization'] = 'Bearer {}'.format(response.json()['result'])

        # search
        data = {'should_get_only_private_analysis': False}
        response = session.get("{}/files/{}".format(URL, analysis.entropy.sha256), json=data)
        url = ""
        if response.ok:
            data = response.json()
            url = "https://analyze.intezer.com{}".format(data.get("result_url", ""))
            det = OnlineDetection()
            result = data.get("result", {})
            if result:
                det.level = DetectionLevel.from_text(result.get("verdict", ""))
                det.name = result.get("family_name", "")
                detections[result.get("analysis_id", "???")] = det
                return OnlineResult(detections=detections, url=url)
            else:
                return None
        elif response.status_code == 404:
            return None
        else:
            response.raise_for_status()
        


