const fs = require('fs')
const jimp = require('jimp')
const { body, validationResult } = require('express-validator')
const LotteryPopUp = require('../models/LotteryPopUp')
const { _sr } = require('../plugins/serverResponses')
const { res500, checkValidations } = require('../plugins/controllersHelperFunctions')

///
const _faSr = _sr.fa

module.exports.modify = [
  [
    body('visible').exists().withMessage(_faSr.required.field).bail().isBoolean().withMessage(_faSr.format.boolean),

    body('x').exists().withMessage(_faSr.required.field).bail().isNumeric().withMessage(_faSr.format.number),

    body('y').exists().withMessage(_faSr.required.field).bail().isNumeric().withMessage(_faSr.format.number)
  ],
  checkValidations(validationResult),
  async (req, res) => {
    const { visible, x, y } = req.body
    let imageName = null

    // check for background image
    if (req.files?.bgImg) {
      const image = req.files.bgImg

      // validate image format
      if (image.mimetype.split('/')[1] !== 'png') {
        return res.status(422).json({ validation: { bgImg: { msg: 'فقط فرمت png قابل قبول است' } } })
      }

      imageName = 'popupBtn_' + Date.now() + '.png'

      jimp
        .read(image.data)
        .then(img => {
          img.quality(100).write(`./static/uploads/images/lottery/${imageName}`)
        })
        .catch(err => {
          console.log(err)
        })
    }

    try {
      const lotteryPopUp = await LotteryPopUp.findOne()

      if (!lotteryPopUp) {
        const data = {
          visible,
          x,
          y
        }
        if (imageName) {
          data.bgImg = imageName
          // get width & height from image
          const imageDimensions = await jimp.read(`./static/uploads/images/lottery/${imageName}`)
          data.w = imageDimensions.bitmap.width
          data.h = imageDimensions.bitmap.height
        }

        await LotteryPopUp.create(data)
        return res.json({ message: _faSr.response.success_save })
      } else {
        if (imageName) {
          lotteryPopUp.bgImg &&
            fs.unlink(`./static/${lotteryPopUp.bgImg}`, err => {
              if (err) console.log(err)
            })

          lotteryPopUp.bgImg = imageName
        }
        lotteryPopUp.visible = visible
        lotteryPopUp.x = x
        lotteryPopUp.y = y

        // get width & height from image
        const imageDimensions = await jimp.read(`./static/${lotteryPopUp.bgImg}`)
        lotteryPopUp.w = imageDimensions.bitmap.width
        lotteryPopUp.h = imageDimensions.bitmap.height

        await lotteryPopUp.save()
        return res.json({ message: _faSr.response.success_save })
      }
    } catch (e) {
      return res500(res, `there is an error here --- ${e}`)
    }
  }
]

module.exports.getPopUpInfo = [
  async (req, res) => {
    try {
      const lotterPopUp = await LotteryPopUp.findOne()
      return res.json(
        lotterPopUp || {
          visible: false,
          x: 15,
          y: 15,
          w: 40,
          h: 40
        }
      )
    } catch (e) {
      return res500(res, `there is an error here --- ${e}`)
    }
  }
]
