import { z } from 'zod';

export default class Conversation  {
    indices = null

    constructor(indices) {
        this.indices = indices
    }

    schema = z.object({
        id: z.number(),
        between: z.array(z.string()),
        lastUpdated: z.string()
    }).strict()

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

    get(convoID) {
        console.log("convo getting, ", convoID)
        return this.entries[this.ids[convoID]]
    }

    getByMember(userID) {
        let convos = []

        function populateMemberProfilesFromIDs(ids) {
            let result = []
            for(let i=0; i<ids.length; i++) {
                result[i] = global.db.members.get(ids[i])
            }
            return result
        }

        for(let i=0; i<this.entries.length; i++) {
            let convo = this.entries[i]
            console.log(convo, userID)
            if(convo.between.includes(userID)) {

                console.log("found user convo: ", convo.id)
                let messages = global.db.messages.getByConversation(`CONVERSATION-${convo.id}`)
                let result = {
                    ...convo,
                    messages,
                }
                result.between = populateMemberProfilesFromIDs(convo.between)
                
                convos.push(result)
            }
        }
        return convos
    }
}