import { z } from 'zod';

export default class Post  {
    indices = null

    constructor(indices) {
        this.indices = indices
    }
    
    schema = z.object({
        text: z.string(),
        time: z.string(),
        sentBy: z.string()
    })

    makeID(forum, number) {
        return `POST-${forum}-${number}`
    }

    save(post, id) {
        let result = this.schema.safeParse(post)
        if(result.success) {
            try {
                super.add(id, post)
            } catch(e) {
                console.error(e)
                throw e
            }
        } else {
            console.error("Failed parsing member: ", result.error)
            throw new global.ServerError(400, "Invalid Member Data!: ");
        }
    }

    get(forum, number) {
        let result = []
        let limit = Math.min(number, this.entries.length)
        for(let i=1; i<=limit; i++) {
            let id = this.makeID(forum, i)
            let post = this.entries[this.ids[id]]
            let {firstName, lastName} = global.db.members.get(post.sentBy)
            let seededObj = {
                ...post
            }
            seededObj.sentByID = post.sentBy
            seededObj.sentBy = firstName + " " + lastName
            result.push(seededObj)
        }
        return result
    }

    async add(text, forum, userEmail) {
        let newPost = {}
        newPost.text = text
        newPost.sentBy = db.members.getIDFromEmail(userEmail)
        newPost.time = global.currentTime()

        let idNumber = this.entries.length+1
        super.add(this.makeID(forum, idNumber), newPost)
    }
}