{"size": 1443, "ext": "js", "max_stars_repo_path": "src/models/img.model.js", "max_stars_repo_name": "ZholobovSS/photostock", "max_stars_repo_stars_event_min_datetime": "2020-09-11T06:04:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-26T20:27:41.000Z", "max_issues_repo_path": "src/models/img.model.js", "max_issues_repo_name": "ZholobovSS/photostock", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/models/img.model.js", "max_forks_repo_name": "ZholobovSS/photostock", "max_forks_repo_forks_event_min_datetime": "2021-05-17T06:58:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-17T06:58:21.000Z"}
{"max_stars_count": 3, "max_issues_count": null, "max_forks_count": 1, "avg_line_length": 30.7021276596, "max_line_length": 85, "alphanum_fraction": 0.7068607069}
const mongoose = require('mongoose')
const fs = require('fs').promises
const path = require('path')
const { addRootDir, appRootDir } = require('../config/const')

const imgShema = mongoose.Schema({
  user: mongoose.Schema.Types.ObjectId,
  description: String,
  path: String,
  raiting: Number,
})

imgShema.statics.star = async function (photoID, userID) {
  const currentImg = await this.findById(photoID).exec()
  const currentUser = await this.model('User').findById(userID)
  const canUserLikePhoto = !currentUser.like.includes(photoID)

  if (canUserLikePhoto) {
    currentImg.raiting++
    await currentImg.save()
    currentUser.like.push(photoID)
    await currentUser.save()

    return true
  }

  return false
}

// TODO: We shoud remove current removing photo from all users like photo array
imgShema.statics.remove = async function (photoID, userID) {
  const currentImg = await this.findOne({ _id: photoID, user: userID }).exec()
  if (currentImg) {
    const currentUser = await this.model('User').findById(userID)
    currentUser.images = currentUser.images.filter((el) => el.toString() !== photoID)
    currentUser.like = currentUser.like.filter((el) => el.toString() !== photoID)
    await currentUser.save()

    await fs.unlink(path.join(appRootDir, 'public', 'img', currentImg.path))
    await this.deleteOne({ _id: photoID })
    return 'OK'
  }
  return 'BAD USER'
}

module.exports = mongoose.model('Img', imgShema)
