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

///////////////////////////////////////// create project
module.exports.create = [
   [
      body('fa_name')
         .notEmpty().withMessage(v_m['fa'].required.title)
         .bail()
         .custom((value, {req}) => {
            return Project.findOne({'project_details.fa.name': value})
               .then(project => {
                  if (project) return Promise.reject(v_m['fa'].duplicated.name)
                  else return true
               })
         }),

      body('en_name')
         .notEmpty().withMessage(v_m['fa'].required.title)
         .bail()
         .custom((value, {req}) => {
            return Project.findOne({'project_details.en.name': value})
               .then(project => {
                  if (project) return Promise.reject(v_m['fa'].duplicated.name)
                  else return true
               })
         }),

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

      const data = {
         date: req.body.date,
         project_details: {
            fa: {
               name: req.body.fa_name,
               description: req.body.fa_description,
            },
            en: {
               name: req.body.en_name,
               description: req.body.en_description,
            }
         },
         created_at: dateFormat(Date.now(), 'yyyy-mm-dd HH:MM:ss')
      }

      const project = new Project(data)
      project.save((err, project) => {
         if (err) console.log(err)
         return res.json(project)
      })
   }
]

///////////////////////////////////////// get all projects
module.exports.getAll = [
   (req, res) => {
      Project.find({}, (err, projects) => {
         if (err) return res.json({errors: err})
         return res.json(projects)
      })
   }
]

///////////////////////////////////////// get one project
module.exports.getOne = [
   (req, res) => {
      Project.findById(req.params.id, (err, project) => {
         if (err) return res.json({errors: err})
         return res.json(project)
      })
   }
]

///////////////////////////////////////// update one project
module.exports.update = [
   [
      body('fa_name')
         .notEmpty().withMessage(v_m['fa'].required.title)
         .bail()
         .custom((value, {req}) => {
            return Project.findOne({'project_details.fa.name': value})
               .then(project => {
                  if (project && project._id.toString() !== req.params.id) return Promise.reject(v_m['fa'].duplicated.name)
                  else return true
               })
         }),

      body('en_name')
         .notEmpty().withMessage(v_m['fa'].required.title)
         .bail()
         .custom((value, {req}) => {
            return Project.findOne({'project_details.en.name': value})
               .then(project => {
                  if (project && project._id.toString() !== req.params.id) return Promise.reject(v_m['fa'].duplicated.name)
                  else return true
               })
         }),

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

      const data = {
         date: req.body.date,
         project_details: {
            fa: {
               name: req.body.fa_name,
               description: req.body.fa_description,
            },
            en: {
               name: req.body.en_name,
               description: req.body.en_description,
            }
         },
         updated_at: dateFormat(Date.now(), 'yyyy-mm-dd HH:MM:ss')
      }

      Project.findByIdAndUpdate(req.params.id, data, (err, oldData) => {
         if (err) console.log(err)
         return res.json({message: v_m['fa'].response.success_save})
      })
   }
]

///////////////////////////////////////// delete project
module.exports.delete = [
   (req, res) => {
      Project.findByIdAndRemove(req.params.id, (err, data) => {
         if (err) return res.json({error: err})
         data.images.forEach(async item => {
            await fs.unlink(`./static/${item.image}`, err => {
               if (err) console.log(err)
            })
         })
         return res.json({message: v_m['fa'].response.success_remove})
      })
   }
]

////////////////////////////////////////////////////////////////////////////////////////

/////////////////////////////// add images to project
module.exports.addImage = [
   (req, res) => {
      Project.findById(req.params.id)
         .then(project => {
            if (!req.files || !req.files.image) return res.status(422).json({validation: {image: {msg: v_m['fa'].required.image}}})

            let fileName = 'project_' + Date.now() + '.' + req.files.image.mimetype.split('/')[1]
            jimp.read(req.files.image.data)
               .then(img => {
                  img
                     .cover(1010, 534)
                     .quality(80)
                     .write(`./static/uploads/images/projects/${fileName}`)

                  ////
                  const data = {
                     image: fileName,
                     created_at: dateFormat(Date.now(), 'yyyy-mm-dd HH:MM:ss')
                  }
                  project.images.push(data)
                  project.save(cb => {
                     return res.json(project)
                  })
               })
               .catch(err => {
                  console.log(err)
               })
         })
   }
]

module.exports.deleteImage = [
   (req, res) => {
      Project.findOne({'images._id': req.params.id}, (err, project) => {
         if (err) console.log(err)
         if (project) {
            let image = project.images.id(req.params.id)
            fs.unlink(`./static/${image.image}`, err => {
               if (err) console.log(err)
               image.remove()
               project.save(cb => {
                  return res.json({message: v_m['fa'].response.success_remove})
               })
            })
         }
      })
   }
]
