import json
import shlex
from multiprocessing.dummy import Process
from subprocess import check_output, CalledProcessError

import database
import settings


class Query(Process):
    def __init__(self, sha256):
        super(Query, self).__init__(name=f'[Analysis] VirusTotalQuery {sha256}')
        self.sha256 = sha256
        self.logger = settings.get_logger('VirusTotal')
        self.logger.debug(f'Created query for {sha256}')

    def run(self):
        self.logger.info(f'Querying VirusTotal for {self.sha256}')
        try:
            output = check_output(shlex.split(
                f"curl -s -S --request GET --url https://www.virustotal.com/api/v3/files/{self.sha256}"
                f" --header 'x-apikey: {settings.VIRUSTOTAL_API_KEY}'"))
            result = json.loads(output)
        except CalledProcessError as e:
            self.logger.error(f'Failed to retrieve VirusTotal information for {self.sha256}:\n{e}')
            return
        database.store_vt(self.sha256, result)
