const History = require('../models/History')
const dateformat = require('dateformat')
const {body, validationResult} = require('express-validator')
const jimp = require('jimp')
const fs = require('fs')
const v_m = require('../validation_messages')

// local variables
const imageWidth = 648
const imageHeight = 443
const imageQuality = 100

module.exports.create = [
  [
    body('fa_title')
       .notEmpty().withMessage(v_m['fa'].required.title),

    body('en_title')
       .notEmpty().withMessage(v_m['fa'].required.title),

    body('year')
       .notEmpty().withMessage(v_m['fa'].required.date)
       .bail()
       .isNumeric().withMessage(v_m['fa'].format.number)
       .bail()
       .isLength({min: 4}).withMessage(v_m['fa'].min_char.min4)
       .bail()
       .isLength({max: 4}).withMessage(v_m['fa'].max_char.max4)
  ],
  (req, res) => {
    const errors = validationResult(req)
    if (!errors.isEmpty()) return res.status(422).json({validation: errors.mapped()})
    if (!req.files || !req.files.image) return res.status(422).json({validation: {image: {msg: v_m['fa'].required.image}}})

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

    const data = {
      image: fileName,
      year: Number(req.body.year),
      history_details: {
        fa: {
          title: req.body.fa_title,
          caption: req.body.fa_caption
        },
        en: {
          title: req.body.en_title,
          caption: req.body.en_caption
        }
      },
      created_at: dateformat(Date.now(), 'yyyy-mm-dd HH:MM:ss')
    }

    jimp.read(req.files.image.data)
       .then(img => {
         img
            .resize(imageWidth, jimp.AUTO)
            .cover(imageWidth, imageHeight)
            .quality(imageQuality)
            .write(`./static/uploads/images/history/${fileName}`, cb => {
              const history = new History(data)
              history.save(err => {
                if (err) console.log(err)
                return res.json(v_m['fa'].response.success_save)
              })
            })
       })
       .catch(err => {
         console.log(err)
       })
  }
]


module.exports.getAll = [
  (req, res) => {
    History.find({}).sort({year: 1}).exec((err, data) => {
      if (err) console.log(err)
      return res.json(data)
    })
  }
]


module.exports.getOne = [
  (req, res) => {
    History.findById(req.params.id, (err, data) => {
      if (err) return res.status(404).json({message: err})
      return res.json(data)
    })
  }
]


module.exports.update = [
  [
    body('fa_title')
       .notEmpty().withMessage(v_m['fa'].required.title),

    body('en_title')
       .notEmpty().withMessage(v_m['fa'].required.title),

    body('year')
       .notEmpty().withMessage(v_m['fa'].required.date)
       .bail()
       .isNumeric().withMessage(v_m['fa'].format.number)
       .bail()
       .isLength({min: 4}).withMessage(v_m['fa'].min_char.min4)
       .bail()
       .isLength({max: 4}).withMessage(v_m['fa'].max_char.max4)
  ],
  (req, res) => {
    const errors = validationResult(req)
    if (!errors.isEmpty()) return res.status(422).json({validation: errors.mapped()})

    const data = {
      year: Number(req.body.year),
      history_details: {
        fa: {
          title: req.body.fa_title,
          caption: req.body.fa_caption
        },
        en: {
          title: req.body.en_title,
          caption: req.body.en_caption
        }
      },
      updated_at: dateformat(Date.now(), 'yyyy-mm-dd HH:MM:ss')
    }

    if (req.files && req.files.image) {
      let fileName = 'history_' + Date.now() + '.' + req.files.image.mimetype.split('/')[1]
      data.image = fileName
      jimp.read(req.files.image.data)
         .then(img => {
           img
              .resize(imageWidth, jimp.AUTO)
              .cover(imageWidth, imageHeight)
              .quality(imageQuality)
              .write(`./static/uploads/images/history/${fileName}`, cb => {
                History.findByIdAndUpdate(req.params.id, data, (err, oldData) => {
                  if (err) console.log(err)
                  fs.unlink(`./static/${oldData.image}`, err => {
                    if (err) console.log(err)
                    return res.json(v_m['fa'].response.success_save)
                  })
                })
              })
         })
         .catch(err => {
           console.log(err)
         })
    } else {
      History.findByIdAndUpdate(req.params.id, data, (err, oldData) => {
        if (err) return res.status(404).json({message: err})
        return res.json(v_m['fa'].response.success_save)
      })
    }
  }
]


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