import { z } from 'zod';

export default class Message  {
    indices = null

    constructor(indices) {
        this.indices = indices
    }

    schema = z.object({
        id: z.number(),
        conversation: z.string(),
        from: z.string(),
        text: z.string(),
        time: z.string()
    }).strict()

    save(msg) {
        let id = `DM-${msg.id}`
        let result = this.schema.safeParse(msg)
        if(result.success) {
            try {
                super.add(id, msg)
            } catch(e) {
                console.error(e)
                throw e
            }
        } else {
            console.error(result.error)
            throw new global.ServerError(400, "Invalid Conversation Data!");
        }
    }

    add(convo, text, userID) {
        let newMessage = {}
        newMessage.time = global.currentTime()
        newMessage.from = userID
        newMessage.conversation = convo
        newMessage.text = text
        newMessage.id = this.entries.length+1
        console.log(newMessage)
        this.save(newMessage)
    }

    getByConversation(convoID) {
        let result = []
        for(let i=0; i<this.entries.length; i++) {
            let entry = this.entries[i]
            if(entry.conversation = convoID) {
                let userID = entry.from
                let fromUser = global.db.members.get(userID)
                let newObj = {
                    ...entry
                }
                newObj.from = fromUser
                result.push(newObj)
            }
        }
        return result
    }
}