text: const Database = require("../db/config")
  
  module.exports = {
    async create(req, res){
      const db = await Database()
      const pass = req.body.password
      let roomId = Math.floor(Math.random() * 10)
      let isRoom = true
  
      while (isRoom) { 
        /* Gera número da sala */
        for (let i = 0; i < 5; i++) {
          roomId += Math.floor(Math.random() * 10).toString();
          
        }
        
        /* Valida pre-existencia do número de sala */
        const roomsExistIds = await db.all(`SELECT id FROM rooms`);      
        isRoom = roomsExistIds.some(roomExistId => roomExistId === roomId)
        
        if (!isRoom) {
          /* Inseri a sala no banco */
          await db.run(`INSERT INTO rooms (
            id,
            pass
            ) VALUES (
              ${Number(roomId)},
              ${pass}
            )`)
              
        }
      }
            
      await db.close()
  
      res.redirect(`/room/${roomId}`)
    },
  
    async open(req, res){
      const db = await Database()
      const roomId = req.params.room
      const questions = await db.all(`SELECT * FROM questions WHERE room = ${roomId} AND read = 0`)
      const questionsRead = await db.all(`SELECT * FROM questions WHERE room = ${roomId} AND read = 1`)
      let isNoQuestions = false
  
      if (questions.length == 0) {
        if (questionsRead.length == 0) {
          isNoQuestions = true
        }
      }
      
      res.render("room", {roomId: roomId, questions: questions, questionsRead: questionsRead, isNoQuestions: isNoQuestions})
    },
  
    async enter(req, res){
      const roomId = req.body.roomId
  
      res.redirect(`/room/${roomId}`)
    }
  }