const { body, validationResult } = require('express-validator')
const Announcement = require('../models/Announcement')
const { _sr } = require('../plugins/serverResponses')
const { res404, res500, checkValidations } = require('../plugins/controllersHelperFunctions')
const { notifyAllUsers } = require('../WebSocket/controllers/user_EventsController')
const { notifyAllAgents } = require('../WebSocket/controllers/agent_EventsController')
const _faSr = _sr.fa
const maxAttachmentSize = 2048

module.exports.create = [
  [
    body('title').notEmpty().withMessage(_faSr.required.title),

    body('caption').notEmpty().withMessage(_faSr.required.caption),

    body('expireDate')
      .notEmpty()
      .withMessage('تاریخ انقضا را مشخص کنید')
      .bail()
      .isNumeric()
      .withMessage('فرمت تاریخ باید timestamp باشد')
      .bail()
      .custom((value, { req }) => {
        if (Number(value) < Date.now()) return Promise.reject(new Error('نمیتوان تاریخ روز جاری یا قبل تر انتخاب کرد.'))
        else return Promise.resolve()
      }),
    body('isForAgents')
      .notEmpty()
      .withMessage('this param is required')
      .bail()
      .isBoolean()
      .withMessage(_faSr.format.boolean)
  ],
  checkValidations(validationResult),
  async (req, res) => {
    const { title, caption, expireDate, isForAgents, publicx } = req.body
    const { user_id } = req
    const data = { title, caption, expireDate, isForAgents, public: publicx, _creator: user_id }
    if (req.files?.image) {
      const image = req.files.image
      const fileName = 'announcement' + Date.now() + '.' + image.name
      const acceptableFormats = ['png', 'jpg', 'jpeg', 'webp']
      if (!acceptableFormats.includes(image.mimetype.split('/')[1]))
        return res.status(422).json({ validation: { image: { msg: _faSr.format.image } } })
      if (image.size / 1024 > maxAttachmentSize)
        return res
          .status(422)
          .json({ validation: { image: { msg: `حجم تصویر نباید بیشتر از ${maxAttachmentSize} KB باشد.` } } })
      data.image = fileName
      await image.mv(`./static/uploads/images/announcement/${fileName}`)
    }

    const announcement = new Announcement(data)
    announcement.save(err => {
      if (err) return res500(res, err)
      if (isForAgents) notifyAllAgents('fetchNewAnnouncements')
      if (!isForAgents) notifyAllUsers('fetchNewAnnouncements')
      return res.json({ message: _faSr.response.success_save })
    })
  }
]

module.exports.getAllForAdmin = [
  (req, res) => {
    Announcement.find({}, (err, notifs) => {
      if (err) return res500(res, err)
      return res.json(notifs)
    })
  }
]

module.exports.getOneForAdmin = [
  async (req, res) => {
    try {
      const announcement = await Announcement.findById(req.params.id)
      return res.json(announcement)
    } catch (e) {
      return res500(res, e)
    }
  }
]

module.exports.getNotifsForUsers = [
  async (req, res) => {
    try {
      const userID = req.user_id
      const announcements = await Announcement.find({ users: { $ne: userID } })
      for await (const item of announcements) {
        item.users.push(userID)
        await item.save()
      }
      return res.json(announcements)
    } catch (e) {
      return res500(res, e)
    }
  }
]

module.exports.getNotifsForSite = [
  async (req, res) => {
    try {
      
      const announcements = await Announcement.find({ public:true })
    
      return res.json(announcements)
    } catch (e) {
      return res500(res, e)
    }
  }
]

module.exports.deleteAnnouncement = [
  (req, res) => {
    Announcement.findByIdAndRemove(req.params.id, (err, oldData) => {
      if (err || !oldData) return res404(res, err)
      return res.json({ message: _faSr.response.success_remove })
    })
  }
]

// module.exports.updateByAdmin = [
//   [
//     body('title')
//        .notEmpty().withMessage(_faSr.required.title),
//
//     body('caption')
//        .notEmpty().withMessage(_faSr.required.caption),
//   ],
//   checkValidations(validationResult),
//   async (req, res) => {
//     try {
//       const {title, caption} = req.body
//       const data = {title, caption, _creator: req.user_id}
//       Announcement.findByIdAndUpdate(req.params.id, data, (err, oldData) => {
//         if (err || !oldData) return res404(res, err)
//         return res.json({message: _faSr.response.success_save})
//       })
//     } catch (e) {
//       return res500(res, e)
//     }
//   }
// ]
