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

// local variables
const shortDescriptionLength = 500

const coverWidth = 1920
const coverHeight = 720
const coverQuality = 70

const thumbWith = 460
const thumbHeight = 320

module.exports.create = [
  [
    // title
    body('fa_title')
       .notEmpty().withMessage(v_m['fa'].required.title)
       .bail()
       .isLength({max: 120}).withMessage(v_m['fa'].max_char.max120)
       .bail()
       .custom((value, {req}) => {
         return BlogPost.findOne({'post_details.fa.title': value}).then(post => {
           if (post) return Promise.reject(v_m['fa'].duplicated.title)
           return true
         })
       }),
    body('en_title')
       .notEmpty().withMessage(v_m['fa'].required.title)
       .bail()
       .isLength({max: 120}).withMessage(v_m['fa'].max_char.max120)
       .bail()
       .custom((value, {req}) => {
         return BlogPost.findOne({'post_details.en.title': value}).then(post => {
           if (post) return Promise.reject(v_m['fa'].duplicated.title)
           return true
         })
       }),

    // description
    body('fa_description')
       .notEmpty().withMessage(v_m['fa'].required.description),
    body('en_description')
       .notEmpty().withMessage(v_m['fa'].required.description),

    // short description
    body('fa_short_description')
       .notEmpty().withMessage(v_m['fa'].required.description),
    body('en_short_description')
       .notEmpty().withMessage(v_m['fa'].required.description),

    body('category')
       .notEmpty().withMessage(v_m['fa'].required.category)
  ],
  (req, res) => {
    const errors = validationResult(req)
    if (!errors.isEmpty()) return res.status(422).json({validation: errors.mapped()})

    let cover
    let coverName

    if (req.files && req.files.cover) {
      cover = req.files.cover
      coverName = 'blog_' + Date.now() + '.' + cover.mimetype.split('/')[1]
    } else {
      return res.status(422).json({validation: {cover: {msg: v_m['fa'].required.cover}}})
    }

    jimp.read(cover.data)
       .then(img => {
         img
            .cover(coverWidth, coverHeight)
            .quality(coverQuality)
            .write(`./static/uploads/images/blog/${coverName}`)
            .resize(thumbWith, jimp.AUTO)
            .cover(thumbWith, thumbHeight)
            .write(`./static/uploads/images/blog/thumb_${coverName}`)
       })

    const data = {
      post_details: {
        fa: {
          title: req.body.fa_title,
          description: req.body.fa_description,
          short_description: req.body.fa_short_description.slice(0, shortDescriptionLength) + ' ... '
        },
        en: {
          title: req.body.en_title,
          description: req.body.en_description,
          short_description: req.body.en_short_description.slice(0, shortDescriptionLength) + ' ... '
        }
      },
      cover: coverName,
      published: req.body.published,
      category: req.body.category,
      created_at: dateformat(Date.now(), 'yyyy-mm-dd HH:MM:ss')
    }

    const post = new BlogPost(data)
    post.save(err => {
      if (err) console.log(err)
      return res.json({message: v_m['fa'].response.success_save})
    })
  }
]


module.exports.getAll = [
  (req, res) => {
    BlogPost.find({}).sort({_id: -1}).exec((err, posts) => {
      if (err) console.log(err)
      return res.json(posts)
    })
  }
]


module.exports.getOne = [
  (req, res) => {
    BlogPost.findById(req.params.id, (err, post) => {
      if (err) console.log(err)
      return res.json(post)
    })
  }
]


module.exports.update = [
  [
    // title
    body('fa_title')
       .notEmpty().withMessage(v_m['fa'].required.title)
       .bail()
       .isLength({max: 120}).withMessage(v_m['fa'].max_char.max120)
       .bail()
       .custom((value, {req}) => {
         return BlogPost.findOne({'post_details.fa.title': value}).then(post => {
           if (post && post._id.toString() !== req.params.id) return Promise.reject(v_m['fa'].duplicated.title)
           return true
         })
       }),
    body('en_title')
       .notEmpty().withMessage(v_m['fa'].required.title)
       .bail()
       .isLength({max: 120}).withMessage(v_m['fa'].max_char.max120)
       .bail()
       .custom((value, {req}) => {
         return BlogPost.findOne({'post_details.en.title': value}).then(post => {
           if (post && post._id.toString() !== req.params.id) return Promise.reject(v_m['fa'].duplicated.title)
           return true
         })
       }),


    // description
    body('fa_description')
       .notEmpty().withMessage(v_m['fa'].required.description),
    body('en_description')
       .notEmpty().withMessage(v_m['fa'].required.description),

    // short description
    body('fa_short_description')
       .notEmpty().withMessage(v_m['fa'].required.description),
    body('en_short_description')
       .notEmpty().withMessage(v_m['fa'].required.description),


    body('category')
       .notEmpty().withMessage(v_m['fa'].required.category)
  ],
  (req, res) => {
    const errors = validationResult(req)
    if (!errors.isEmpty()) return res.status(422).json({validation: errors.mapped()})


    const data = {
      post_details: {
        fa: {
          title: req.body.fa_title,
          description: req.body.fa_description,
          short_description: req.body.fa_short_description.slice(0, shortDescriptionLength) + ' ... '
        },
        en: {
          title: req.body.en_title,
          description: req.body.en_description,
          short_description: req.body.en_short_description.slice(0, shortDescriptionLength) + ' ... '
        }
      },
      published: req.body.published,
      category: req.body.category,
      updated_at: dateformat(Date.now(), 'yyyy-mm-dd HH:MM:ss')
    }

    let cover
    let coverName

    if (req.files && req.files.cover) {
      cover = req.files.cover
      coverName = 'blog_' + Date.now() + '.' + cover.mimetype.split('/')[1]

      data.cover = coverName
      jimp.read(cover.data)
         .then(img => {
           img
              .cover(coverWidth, coverHeight)
              .quality(coverQuality)
              .write(`./static/uploads/images/blog/${coverName}`)
              .resize(thumbWith, jimp.AUTO)
              .cover(thumbWith, thumbHeight)
              .write(`./static/uploads/images/blog/thumb_${coverName}`)
         })
    }

    BlogPost.findByIdAndUpdate(req.params.id, data, (err, oldData) => {
      if (err) console.log(err)
      if (cover && cover.data) {
        fs.unlink(`./static/${oldData.cover}`, err => {
          if (err) console.log(err)
        })
        fs.unlink(`./static/${oldData.thumb}`, err => {
          if (err) console.log(err)
        })
      }
      BlogPost.findById(oldData._id, (err, newData) => {
        if (err) console.log(err)
        return res.json(newData)
      })
    })
  }
]


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