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

import {
    default as ValidateSchema
} from 'validate'

import {
    randomBytes
} from "crypto";


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

const authoritySchema = new ValidateSchema({
    name: {
        type: String,
        required: true,
        match: /^[a-zA-Z0-9\ \-\_]+$/,
        length: { min: 3, max: 32 },
        message: 'invalid name'
    }
})

export async function saveAuthority(authorityID, authorityConfig) {
    let configErrorList = authoritySchema.validate(authorityConfig);
    
    configErrorList = configErrorList.map((configError) => {
        return configError.message;
    })

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

    await authorityDB.push(`/${authorityID}`, authorityConfig);

    return {
        status: "ok"
    }
}

export async function getAuthority(authorityID) {
    let AuthorityData = await authorityDB.getData(`/${authorityID}`);
    return AuthorityData;
}

export async function deleteAuthority(authorityID) {
    await authorityDB.delete(`/${authorityID}`);
}

saveAuthority(randomBytes(4).toString("hex"), {names: "{test}"})