const MainCatalog = require('../models/MainCatalog')
const dateformat = require('dateformat')
const v_m = require('../validation_messages')
const fs = require('fs')

module.exports.create = [
  (req, res) => {
    if (!req.files || !req.files.pdf) return res.status(422).json({validation: {pdf: {msg: v_m['fa'].required.file}}})
    if (req.files.pdf.mimetype.split('/')[1] !== 'pdf') return res.status(422).json({validation: {pdf: {msg: v_m['fa'].file_types.pdf}}})


    MainCatalog.find({}, (err, catalogs) => {
      if (catalogs.length) {
        let firstFile = catalogs[0]

        if (firstFile.file[req.body.locale]) fs.unlink(`./static/${firstFile.file[req.body.locale]}`, err => {
          if (err) console.log(err)
        })

        firstFile.file[req.body.locale] = req.body.locale + '_' + req.files.pdf.name
        firstFile.updated_at = dateformat(Date.now(), 'yyyy-mm-dd HH:MM:ss')
        firstFile.save((err1, data) => {
          if (err1) console.log(err1)
          req.files.pdf.mv(`./static/uploads/pdf/${req.body.locale}_${req.files.pdf.name}`)
          return res.json(firstFile)
        })


      } else {
        const data = {created_at: dateformat(Date.now(), 'yyyy-mm-dd HH:MM:ss'), file: {}}
        data.file[req.body.locale] = req.body.locale + '_' + req.files.pdf.name

        new MainCatalog(data).save((err, data) => {
          if (err) console.log(err)
          req.files.pdf.mv(`./static/uploads/pdf/${req.body.locale}_${req.files.pdf.name}`)
          return res.json(data)
        })
      }
    })

  }
]

module.exports.get = [
  (req, res) => {
    MainCatalog.find({}, (err, catalog) => {
      if (err) console.log(err)
      if (catalog.length) return res.json(catalog[0])
      else return res.json({})
    })
  }
]
