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

module.exports.create = [
  [
    body('fa_name')
       .notEmpty().withMessage(v_m['fa'].required.title)
       .bail()
       .custom((value, {req}) => {
         return BlogCategory.findOne({'blogCategory_details.fa.name': value}).then(category => {
           if (category) return Promise.reject(v_m['fa'].duplicated.title)
           return true
         })
       }),
    body('en_name')
       .notEmpty().withMessage(v_m['fa'].required.title)
       .bail()
       .custom((value, {req}) => {
         return BlogCategory.findOne({'blogCategory_details.en.name': value}).then(category => {
           if (category) return Promise.reject(v_m['fa'].duplicated.title)
           return true
         })
       })
  ],
  (req, res) => {
    const errors = validationResult(req)
    if (!errors.isEmpty()) return res.status(422).json({validation: errors.mapped()})

    const blogCategory = new BlogCategory({
      blogCategory_details: {
        fa: {
          name: req.body.fa_name
        },
        en: {
          name: req.body.en_name
        }
      },
      created_at: dateformat(Date.now(), 'yyyy-mm-dd HH:MM:ss')
    })
    blogCategory.save(err => {
      if (err) console.log(err)
      return res.json({message: v_m['fa'].response.success_save})
    })
  }
]


module.exports.getAll = [
  (req, res) => {
    BlogCategory.find({}, (err, categories) => {
      if (err) return res.status(500).json({message: err})
      return res.json(categories)
    })
  }
]


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


module.exports.update = [
  [
    body('fa_name')
       .notEmpty().withMessage(v_m['fa'].required.title)
       .bail()
       .custom((value, {req}) => {
         return BlogCategory.findOne({'blogCategory_details.fa.name': value}).then(category => {
           if (category && category._id.toString() !== req.params.id) return Promise.reject(v_m['fa'].duplicated.title)
           return true
         })
       }),
    body('en_name')
       .notEmpty().withMessage(v_m['fa'].required.title)
       .bail()
       .custom((value, {req}) => {
         return BlogCategory.findOne({'blogCategory_details.en.name': value}).then(category => {
           if (category && category._id.toString() !== req.params.id) return Promise.reject(v_m['fa'].duplicated.title)
           return true
         })
       })
  ],
  (req, res) => {
    const errors = validationResult(req)
    if (!errors.isEmpty()) return res.status(422).json({validation: errors.mapped()})

    const data = {
      blogCategory_details: {
        fa: {
          name: req.body.fa_name
        },
        en: {
          name: req.body.en_name
        }
      },
      updated_at: dateformat(Date.now(), 'yyyy-mm-dd HH:MM:ss')
    }
    BlogCategory.findByIdAndUpdate(req.params.id, data, (err, oldData) => {
      if (err) console.log(err)
      return res.json({message: v_m['fa'].response.success_save})
    })
  }
]


module.exports.delete = [
  (req, res) => {
    BlogPost.find({category: req.params.id}, (err, posts) => {
      if (err) console.log(err)
      if (!posts.length) {
        BlogCategory.findByIdAndDelete(req.params.id, (err) => {
          if (err) return res.status(404).json({message: err})
          return res.json({message: v_m['fa'].response.success_save})
        })
      } else {
        return res.status(500).json({message: 'نمیتوان دسته بندی هایی که دارای پست هستند را پاک کرد.'})
      }
    })
  }
]
