{"size": 6093, "ext": "js", "max_stars_repo_path": "controllers/post.controller.js", "max_stars_repo_name": "LaurentSanson/reseau-social", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "controllers/post.controller.js", "max_issues_repo_name": "LaurentSanson/reseau-social", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "controllers/post.controller.js", "max_forks_repo_name": "LaurentSanson/reseau-social", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 23.0795454545, "max_line_length": 145, "alphanum_fraction": 0.5271623174}
const PostModel = require('../models/post.model');
const UserModel = require('../models/user.model');
const {uploadErrors} = require("../utils/errors.utils");
const ObjectId = require('mongoose').Types.ObjectId;
const fs = require('fs');
const {promisify} = require('util');
const pipeline = promisify(require('stream').pipeline);

module.exports.readPost = (req, res) => {
  PostModel.find((err, docs) => {
    if (!err) {
      res.send(docs);
    } else {
      console.log('Error to get data : ' + err);
    }
  }).sort({createdAt: -1});
}

module.exports.createPost = async (req, res) => {
  let filename;
  if (req.file !== null) {
    try {
      if (req.file.detectedMimeType !== "image/jpg" && req.file.detectedMimeType !== "image/png" && req.file.detectedMimeType !== "image/jpeg") {
        throw Error("invalid file");
      }
      if (req.file.size > 500000) {
        throw Error("max size");
      }
    } catch (err) {
      const errors = uploadErrors(err)
      return res.status(201).json({errors});
    }

    filename = req.body.posterId + Date.now() + '.jpg';

    await pipeline(
      req.file.stream,
      fs.createWriteStream(
        `${__dirname}/../client/public/uploads/post/${filename}`
      )
    );

  }

  const newPost = new PostModel({
    posterId: req.body.posterId,
    message: req.body.message,
    picture: req.file !== null ? "./uploads/posts/" + filename : "",
    video: req.body.video,
    likers: [],
    comments: [],
  });

  try {
    const post = await newPost.save();
    res.status(201).json(post);
  } catch (err) {
    res.status(200).send(err);
  }
}

module.exports.updatePost = (req, res) => {
  if (!ObjectId.isValid(req.params.id)) {
    return res.status(400).send('ID unknown : ' + req.params.id)
  }
  const updatedRecord = {
    message: req.body.message
  }
  PostModel.findByIdAndUpdate(
    req.params.id,
    {$set: updatedRecord},
    {new: true},
    (err, docs) => {
      if (!err) {
        res.send(docs);
      } else {
        console.log("Update error : " + err);
      }
    }
  )
}

module.exports.deletePost = (req, res) => {
  if (!ObjectId.isValid(req.params.id)) {
    return res.status(400).send('ID unknown : ' + req.params.id)
  }
  PostModel.findByIdAndRemove(
    req.params.id,
    (err, docs) => {
      if (!err) {
        res.send(docs);
      } else {
        console.log("Delete error : " + err)
      }
    }
  )
}

module.exports.likePost = async (req, res) => {
  if (!ObjectId.isValid(req.params.id)) {
    return res.status(400).send('ID unknown : ' + req.params.id)
  }

  try {
    await PostModel.findByIdAndUpdate(
      req.params.id,
      {
        $addToSet: {likers: req.body.id}
      },
      {new: true},
      (err, docs) => {
        if (err) {
          return res.status(400).send(err);
        }
      }
    );
    await UserModel.findByIdAndUpdate(
      req.body.id,
      {
        $addToSet: {likes: req.params.id}
      },
      {new: true},
      (err, docs) => {
        if (!err) {
          return res.status(200).send(docs);
        } else {
          return res.status(400).send(err);
        }
      }
    );
  } catch (err) {
    return res.status(400).send(err);
  }
}

module.exports.unlikePost = async (req, res) => {
  if (!ObjectId.isValid(req.params.id)) {
    return res.status(400).send('ID unknown : ' + req.params.id)
  }

  try {
    await PostModel.findByIdAndUpdate(
      req.params.id,
      {
        $pull: {likers: req.body.id}
      },
      {new: true},
      (err, docs) => {
        if (err) {
          return res.status(400).send(err);
        }
      }
    );
    await UserModel.findByIdAndUpdate(
      req.body.id,
      {
        $pull: {likes: req.params.id}
      },
      {new: true},
      (err, docs) => {
        if (!err) {
          return res.status(200).send(docs);
        } else {
          return res.status(400).send(err);
        }
      }
    );
  } catch (err) {
    return res.status(400).send(err);
  }
}

module.exports.commentPost = (req, res) => {
  if (!ObjectId.isValid(req.params.id)) {
    return res.status(400).send('ID unknown : ' + req.params.id)
  }

  try {
    return PostModel.findByIdAndUpdate(
      req.params.id,
      {
        $push: {
          comments: {
            commenterId: req.body.commenterId,
            commenterPseudo: req.body.commenterPseudo,
            text: req.body.text,
            timestamp: new Date().getTime(),
          }
        }
      },
      {new: true},
      (err, docs) => {
        if (!err) {
          return res.status(200).send(docs);
        } else {
          return res.status(400).send(err);
        }
      }
    )
  } catch (err) {
    return res.status(400).send(err)
  }
}

module.exports.editCommentPost = (req, res) => {
  if (!ObjectId.isValid(req.params.id)) {
    return res.status(400).send('ID unknown : ' + req.params.id)
  }

  try {
    return PostModel.findById(
      req.params.id,
      (err, docs) => {
        const theComment = docs.comments.find((comment) =>
          comment._id.equals(req.body.commentId)
        )

        if (!theComment) {
          return res.status(404).send('Comment not found')
        }
        theComment.text = req.body.text;
        return docs.save((err) => {
          if (!err) {
            return res.status(200).send(docs);
          } else {
            return res.status(500).send(err);
          }
        })
      }
    )
  } catch (err) {
    return res.status(400).send(err);
  }
}

module.exports.deleteCommentPost = (req, res) => {
  if (!ObjectId.isValid(req.params.id)) {
    return res.status(400).send('ID unknown : ' + req.params.id)
  }

  try {
    return PostModel.findByIdAndUpdate(
      req.params.id,
      {
        $pull: {
          comments: {
            _id: req.body.commentId
          }
        }
      },
      {new: true},
      (err, docs) => {
        if (!err) {
          return res.status(200).send(docs);
        } else {
          return res.status(400).send(err)
        }
      }
    )

  } catch (err) {
    return res.status(400).send(err);
  }
}