const TransactionDrafts = require('../../models/TransactionDraft')
const TicketConversation = require('../../models/TicketConversation')
const Announcement = require('../../models/Announcement')

module.exports.getAllNotifs = async socket => {
  try {
    const drafts = await TransactionDrafts.find({ user_id: socket.userId })
    const unreadTickets = await TicketConversation.find({
      user_id: socket.userId,
      messages: { $elemMatch: { isUser: false, read: false } }
    })

    socket.emit(`user:allNotifs`, {
      unreadTickets: unreadTickets.length,
      draftsCount: drafts.length
    })
  } catch (e) {
    console.log(e)
  }
}

module.exports.notifyUser = async (type, user_id) => {
  try {
    const io = global._io
    const user = io.of('/user')
    const data = { type }

    if (type === 'updateUnreadTickets') {
      const unreadTickets = await TicketConversation.find({
        user_id,
        messages: { $elemMatch: { isUser: false, read: false } }
      })

      data.unreadTickets = unreadTickets.length
    }
    if (type === 'updateDraftsCount') {
      const drafts = await TransactionDrafts.find({ user_id })
      data.draftsCount = drafts.length
    }

    user.to(user_id.toString()).emit(`user:notify`, data)
  } catch (e) {
    console.log(e)
  }
}

module.exports.notifyAllUsers = type => {
  try {
    const io = global._io
    const user = io.of('/user')
    const data = { type }

    user.emit(`user:notifyAll`, data)
  } catch (e) {
    console.log(e)
  }
}

module.exports.fetchAnnouncements = async socket => {
  try {
    const announcements = await Announcement.find({ expired: false, isForAgents: false })
    const modifiedAnnouncements = []
    let newAnnouncementsCount = 0
    for await (const announcement of announcements) {
      const notif = { ...announcement._doc, seen: true }
      if (!notif.seenBy.includes(socket.userId)) {
        notif.seen = false
        newAnnouncementsCount++
      }
      delete notif.seenBy
      delete notif.expired
      delete notif.isForAgents
      delete notif._creator
      modifiedAnnouncements.push(notif)
    }

    socket.emit('user:announcements', {
      newUserAnnosCount: newAnnouncementsCount,
      userAnnouncements: modifiedAnnouncements.reverse()
    })
  } catch (e) {
    console.log(e)
  }
}

module.exports.updateAnnouncement = async (socket, id) => {
  try {
    if (id) {
      const announcment = await Announcement.findById(id)
      if (!announcment) throw new Error('invalid announcemnet id')
      if (!announcment.seenBy.includes(socket.userId)) announcment.seenBy.push(socket.userId)
      await announcment.save()
      socket.emit('user:fetchNewAnnouncements')
    }
  } catch (e) {
    console.log(e)
  }
}
