const chatService = require("../service/chat.service")

module.exports = {getMessage, addMessage, getConversation}

function getMessage(req, res){
    let body = req.body
    if(!body.sender || !body.receiver || !body.password){
        res.status(400).json({})
        return
    }
    chatService.getMessage(body.sender, body.receiver, body.password).then(messages => res.json(messages))
        .catch(err => res.status(400).json({message: err}))

}

function addMessage(req, res){
    let body = req.body
    if(!body.sender || !body.receiver || !body.password || !body.content){
        res.status(400).json({})
        return
    }
    chatService.addMessage(body.content, body.sender, body.receiver, body.password)
        .then(()=>{
            chatService.getMessage(body.sender, body.receiver, body.password).then(messages => res.json(messages))
        }).catch(err => res.status(400).json({message: err}))
}

function getConversation(req, res){
    let body = req.body
    if(!body.userID || !body.password){
        res.status(400).json({})
        return
    }
    chatService.getConversation(body.userID, body.password).then(cons => res.json(cons))
        .catch(err => res.status(400).json({message: err}))
}