import struct
from transforms.arithmetic import Xor
from filetypes import ordinals

ords = {
    "ws2_32.dll": "imphash_ws2_32.dll",
    "wsock32.dll": "imphash_ws2_32.dll",
    "oleaut32.dll": "imphash_oleaut32",
}

exts = ["ocx", "sys", "dll"]


def get_imphash_string(parser):
    if parser.__class__.name != "PE" or not hasattr(parser, "raw_imports"):
        # imphash only works with PE files
        return ""
    res = []
    translator = ordinals.OrdinalTranslator()

    for dll_raw_name, api in parser.raw_imports:
        parts = dll_raw_name.rsplit(".", 1)
        if len(parts) > 1 and parts[1] in exts:
            libname  = parts[0]
        else:
            libname  = dll_raw_name

        if type(api) == int:
            ordid = api
            api = "ord{}".format(ordid)
            fake_name = ords.get(dll_raw_name)
            if fake_name is not None:
                translation = translator.translate(dll_raw_name, ordid)
                if translation:
                    api = translation
        res.append("{}.{}".format(libname, api.lower()))
    return ",".join(res)


def get_richhash_data(ft):
    if "RichHeader" in ft:
        rich = ft["RichHeader"]
        return Xor().run(rich.bytes[:-8], rich["XorKey"], width="dword")
    return b""
