import * as pkcs11 from "pkcs11js";
import * as core from "./core";
import { SlotCollection } from "./slot";
export class Module extends core.BaseObject {
    constructor(lib) {
        super(lib);
        this.libFile = "";
        this.libName = "";
    }
    static load(libFile, libName) {
        const lib = new pkcs11.PKCS11();
        lib.load(libFile);
        const module = new Module(lib);
        module.libFile = libFile;
        module.libName = libName || libFile;
        return module;
    }
    initialize(options) {
        try {
            this.lib.C_Initialize(options);
        }
        catch (e) {
            if (!/CKR_CRYPTOKI_ALREADY_INITIALIZED/.test(e.message)) {
                throw e;
            }
        }
        this.getInfo();
    }
    finalize() {
        this.lib.C_Finalize();
    }
    getSlots(index, tokenPresent = true) {
        if (!core.isEmpty(index) && core.isBoolean(index)) {
            tokenPresent = index;
        }
        const arr = this.lib.C_GetSlotList(tokenPresent);
        const col = new SlotCollection(arr, this, this.lib);
        if (core.isNumber(index)) {
            return col.items(index);
        }
        return col;
    }
    close() {
        this.lib.close();
    }
    getInfo() {
        const info = this.lib.C_GetInfo();
        this.cryptokiVersion = info.cryptokiVersion;
        this.manufacturerID = core.removePadding(info.manufacturerID);
        this.libraryDescription = core.removePadding(info.libraryDescription);
        this.flags = info.flags;
        this.libraryVersion = info.libraryVersion;
    }
}
