# -*- coding: UTF-8 -*-
import re
import threading

from .__common__ import hashtype, API


__all__ = ["MalwareFeed"]


class MalwareFeed(API):
    doc = "https://github.com/MalwareSamples/Malware-Feed/blob/master/README.md"
    url = "https://api.github.com/repos/MalwareSamples/Malware-Feed"
    _auth_method = "Bearer"
    _pre_condition = lambda s: s.hash in s._paths.keys()
    _headers = {'Accept': "application/vnd.github+json"}
    
    def get_malware_feed(self):
        with threading.Lock() as lock:
            MalwareFeed._paths = {}
            self._get("branches/master")
            self._get(f"git/commits/{self.json['commit']['sha']}")
            self._get(f"git/trees/{self.json['tree']['sha']}", params={'recursive': 1})
            for item in self.json['tree']:
                h = item['path'].split("/")[-1]
                if re.match(r"^[0-9a-f]{64}$", h, re.I):
                    MalwareFeed._paths[h] = item['path']
    
    @hashtype("sha256")
    def get_file_by_hash(self, hash):
        try:
            MalwareFeed._paths
        except AttributeError:
            self.get_malware_feed()
        self._get(f"contents/{MalwareFeed._paths.get(hash)}")._decode("base64")._save()

