
import {
    JsonDB,
    Config
} from 'node-json-db';

import {
    default as ValidateSchema
} from 'validate'


var certificateDB = new JsonDB(new Config("datastore/database/certificates.json", true, true, '/'));

const certificateSchema = new ValidateSchema({
    displayName: {
        type: String,
        required: true,
        match: /^[a-zA-Z0-9\ \-\_\.]+$/,
        message: {
            type: '[displayName] must be a string.',
            required: '[displayName] is required.',
            match: '[displayName] is invalid.'
        }
    },
    certificateType: {
        type: String,
        required: true,
        enum: [
            'rootCA',
            'intermediateCA',
            'identity'
        ],
        message: {
            type: '[certificateType] must be a string.',
            required: '[certificateType] is required.',
            enum: '[certificateType] must be one of [rootCA|intermediateCA|identity]'
        }
    }
})

export async function saveCertificate(sCertificateID, oCertificateData) {
    console.log("-----------------------------------------");
    let configErrorList = certificateSchema.validate(oCertificateData);

    configErrorList = configErrorList.map((configError) => {
        return configError.message;
    })

    console.log(configErrorList);

    if (configErrorList.length > 0) {
        return {
            status: "error",
            errors: configErrorList
        }
    }

    await certificateDB.push(`/${sCertificateID}`, oCertificateData);

    console.log(oCertificateData);

    setTimeout(() => {
        
    }, 5000);

    return {
        status: "ok"
    }
}

export async function getCertificateByID(sCertificateID) {
    let oCertificateData = await certificateDB.getData(`/${sCertificateID}`);
    return oCertificateData;
}

export async function getAllCertificates() {
    let aCertificateList = await certificateDB.getData(`/`);
    return aCertificateList;
}

export async function getCertificatesOfType(sCertificateType) {
    let aCertificateList = await certificateDB.getData(`/`);
    aCertificateList = aCertificateList.filter((oCertificateData) => {
        return oCertificateData.certificateType == sCertificateType;
    })
    return aCertificateList;
}

export async function deleteCertificate(sCertificateID) {
    await certificateDB.delete(`/${sCertificateID}`);
}
