import OrderedObject from "./OrderedObject.js"

export default class Titles extends OrderedObject {

    save(newTitle) {
        let id = `HY-${this.entries.length+1}`
        if(this.validate(id, newTitle)) {
            try {
                super.add(id, newTitle)
            } catch(e) {
                console.error(e)
                throw e
            }
        } else {
            throw new global.ServerError(400, "Invalid Member Data!");
        }
    }

    validate(id, node) {
        let checkID = () => {
            let split = id.split("-")
            return (
                split.length === 2 
                && split[0] === "HY" 
                && !isNaN(Number(split[1]))
            )
        }
        let idres = checkID()
        if(!idres) {
            return false
        }
        
        let checkFields = () => {
            let fields = [
                "fullName",
            ]
            for(let i = 0; i < fields.length; i++) {
                if(!node[fields[i]]) {
                    throw new Error(`Title ${id} is missing trait ${fields[i]}`)
                    return false
                }
            }
            return true
        }
        let fieldres = checkFields()
        if(!fieldres) {
            return false
        }
        
        return true
    }
}