import json
import platform

from libs.pymuffet import muffet


def check_cmd(cmd):
    import shutil
    r = shutil.which(cmd)
    return r is not None

class Filter(muffet.ScanFilter):
    def is_target(self, file: muffet.TFile):
        return file.extension == 'json'


class NT_Detect:


    def __init__(self, osa, common_data_dir):
        self.profile = None
        self.os_profiles = []
        self.data_dir = f'{common_data_dir}'
        self.osa = osa
        self.loadProfiles(self.data_dir)


    def loadProfiles(self, data_dir):
        conf = muffet.MuffetConf()
        conf.input = self.data_dir

        m = muffet.Muffet(conf)
        m.scan(Filter())

        for r in m.scanResults:
            d = self.osa.files.read_str(r.path)
            j = json.loads(d)

            self.os_profiles.append(j)
        os_id = platform.system()

        r = []
        for p in self.os_profiles:
            a = p.get('id').lower()
            if a == os_id.lower():
                r.append(p)

        set_profile = r[0]

        set_profile['release'] = platform.release()
        set_profile['version'] = platform.version()
        set_profile['arch'] = platform.machine()
        if set_profile is None:
            self.osa.log.f("Distribution profile not found.")
        self.osa.log.d(f'Select family == {set_profile.get("family")}, id == {set_profile.get("id")}, release == {set_profile.get("release")}')
        
        self.profile = set_profile
