var PhotoModel = require('../models/photoModel.js');

/**
 * photoController.js
 *
 * @description :: Server-side logic for managing photos.
 */
module.exports = {

  /**
   * photoController.list()
   */
  list: function (req, res) {
    PhotoModel.find()
      .then(photos => {
        var data = {
          photos: photos
        };
        return res.render('photo/list', data);
      })
      .catch(err => {
        return res.status(500).json({
          message: 'Error when getting photos.',
          error: err
        });
      });
  },

  /**
   * photoController.show()
   */
  show: function (req, res) {
    var id = req.params.id;

    PhotoModel.findOne({ _id: id }, function (err, photo) {
      if (err) {
        return res.status(500).json({
          message: 'Error when getting photo.',
          error: err
        });
      }

      if (!photo) {
        return res.status(404).json({
          message: 'No such photo'
        });
      }

      return res.json(photo);
    });
  },

  /**
   * photoController.create()
   */
  create: function (req, res) {
    var photo = new PhotoModel({
      name: req.body.name,
      path: "/UpImage/" + req.file.filename,
    });

    photo.save()
      .then(savedPhoto => {
        // Handle successful save operation
        return res.redirect('/photos');
      })
      .catch(err => {
        return res.status(500).json({
          message: 'Error when creating photo',
          error: err
        });
      });
  },

  /**
   * photoController.update()
   */
  update: function (req, res) {
    var id = req.params.id;

    PhotoModel.findOne({ _id: id })
      .then(photo => {
        if (!photo) {
          return res.status(404).json({
            message: 'No such photo'
          });
        }

        photo.name = req.body.name ? req.body.name : photo.name;
        photo.path = req.body.path ? req.body.path : photo.path;
        return photo.save();
      })
      .then(updatedPhoto => {
        return res.json(updatedPhoto);
      })
      .catch(err => {
        return res.status(500).json({
          message: 'Error when updating photo.',
          error: err
        });
      });
  },

  /**
   * photoController.remove()
   */
  remove: function (req, res) {
    var id = req.params.id;

    PhotoModel.findByIdAndRemove(id, function (err, photo) {
      if (err) {
        return res.status(500).json({
          message: 'Error when deleting the photo.',
          error: err
        });
      }

      return res.status(204).json();
    });
  },

  publish: function (req, res) {
    return res.render('photo/publish');
  }
};