const fs = require('fs')
const { body, validationResult } = require('express-validator')
const jimp = require('jimp')
const Warranty = require('../models/WarrantyTerms')
const { _sr } = require('../plugins/serverResponses')
const { res404, checkValidations } = require('../plugins/controllersHelperFunctions')
const _faSr = _sr.fa

const shortDescriptionLength = 200
const paginateLimit = 10

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

    body('short_description').notEmpty().withMessage(_faSr.required.description),

    body('description').notEmpty().withMessage(_faSr.required.description)
  ],
  checkValidations(validationResult),
  (req, res) => {
    if (!req.files || !req.files.image)
      return res.status(422).json({ validation: { image: { msg: _faSr.required.image } } })

    const image = req.files.image
    const fileName = 'warranty_' + Date.now() + '.' + image.mimetype.split('/')[1]

    // validate image format
    const supportedFormats = ['jpg', 'jpeg', 'png', 'webp']
    if (!supportedFormats.includes(image.mimetype.split('/')[1])) {
      return res.status(422).json({ validation: { image: { msg: _faSr.format.image } } })
    }

    const data = {
      _creator: req.user_id,
      title: req.body.title,
      short_description: req.body.short_description.slice(0, shortDescriptionLength),
      description: req.body.description,
      image: fileName
    }

    jimp
      .read(image.data)
      .then(img => {
        img.cover(350, 350).write(`./static/uploads/images/warrantyTerms/${fileName}`, cb => {
          const warranty = new Warranty(data)
          warranty.save(err => {
            if (err) console.log(err)
            return res.json({ message: _faSr.response.success_save })
          })
        })
      })
      .catch(err => {
        console.log(err)
      })
  }
]

module.exports.getAll = [
  (req, res) => {
    Warranty.paginate({}, { page: req.params?.page || 1, limit: paginateLimit }, (err, result) => {
      if (err) return res.status(404).json({ message: _faSr.not_found.item_id })
      if (!result.docs.length && Number(req.params.page) !== 1)
        return res.status(404).json({ message: _faSr.not_found.item_id })
      else return res.json(result)
    })
  }
]

module.exports.getOne = [
  (req, res) => {
    Warranty.findById(req.params.id)
      .populate('_creator', 'first_name last_name')
      .exec((err, data) => {
        if (err) return res.status(404).json({ message: err })
        return res.json(data)
      })
  }
]

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

    body('short_description').notEmpty().withMessage(_faSr.required.description),

    body('description').notEmpty().withMessage(_faSr.required.description)
  ],
  checkValidations(validationResult),
  (req, res) => {
    const data = {
      _creator: req.user_id,
      title: req.body.title,
      short_description: req.body.short_description.slice(0, shortDescriptionLength),
      description: req.body.description
    }

    if (req.files && req.files.image) {
      const image = req.files.image
      const fileName = 'warranty_' + Date.now() + '.' + image.mimetype.split('/')[1]

      // validate image format
      const supportedFormats = ['jpg', 'jpeg', 'png', 'webp']
      if (!supportedFormats.includes(image.mimetype.split('/')[1])) {
        return res.status(422).json({ validation: { image: { msg: _faSr.format.image } } })
      }

      data.image = fileName

      jimp
        .read(image.data)
        .then(img => {
          img.cover(350, 350).write(`./static/uploads/images/warrantyTerms/${fileName}`)
        })
        .catch(err => {
          console.log(err)
        })
    }

    Warranty.findByIdAndUpdate(req.params.id, data, (err, oldData) => {
      if (err) return res404(res, err)
      if (req.files && req.files.image)
        fs.unlink(`./static/${oldData.image}`, err => {
          if (err) console.log(err)
        })
      Warranty.findById(req.params.id, (err, data) => {
        if (err) return res404(res, err)
        return res.json(data)
      })
    })
  }
]

module.exports.delete = [
  (req, res) => {
    Warranty.findByIdAndDelete(req.params.id, (err, data) => {
      if (err) return res.status(404).json({ message: _faSr.not_found.item_id })
      fs.unlink(`./static/${data.image}`, err => {
        if (err) console.log(err)
      })
      return res.json({ message: _faSr.response.success_remove })
    })
  }
]
