{"size": 2121, "ext": "js", "max_stars_repo_path": "server/models/Album.js", "max_stars_repo_name": "aliciaoshzyx/rm2project3", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "server/models/Album.js", "max_issues_repo_name": "aliciaoshzyx/rm2project3", "max_issues_repo_issues_event_min_datetime": "2020-09-04T19:48:21.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-08T13:16:54.000Z", "max_forks_repo_path": "server/models/Album.js", "max_forks_repo_name": "aliciaoshzyx/rm2project3", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": 3, "max_forks_count": null, "avg_line_length": 18.7699115044, "max_line_length": 99, "alphanum_fraction": 0.627534182}
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const _ = require('underscore');

let AlbumModel = {};

const convertId = mongoose.Types.ObjectId;
const setName = (name) => _.escape(name).trim();

const AlbumSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    trim: true,
    set: setName,
  },

  artist: {
    type: String,
    required: true,
  },

  art: {
    type: String,
    required: true,
  },

  genere: {
    type: String,
    required: true,
  },

  tracks: [{
    type: String,
    required: true,
  }],

  trackPrevs: [{
    type: String,
    required: true,
  }],

  upvotes: {
    type: Number,
    required: false,
    default: 0,
  },

  owner: {
    type: mongoose.Schema.ObjectId,
    required: true,
    ref: 'Account',
  },

  createdData: {
    type: Date,
    default: Date.now,
  },

  user: {
    type: String,
    required: true,
  },
});

AlbumSchema.statics.toAPI = (doc) => ({
  name: doc.name,
  artist: doc.artist,
  art: doc.art,
  genere: doc.genere,
  tracks: doc.tracks,
  trackPrevs: doc.trackPrev,
  owner: doc.owner,
  user: doc.user,
  upvotes: doc.upvotes,
});

AlbumSchema.statics.findAll = (callback) => AlbumModel.find().sort({ upvotes: -1 }).exec(callback);

AlbumSchema.statics.findByOwner = (ownerId, callback) => {
  const search = {
    owner: convertId(ownerId),
  };

  return AlbumModel.find(search)
  .select('name artist art genere tracks trackPrevs owner user').exec(callback);
};

AlbumSchema.statics.updateUpvotes = (albumID, upvotes, callback) => {
  const search = {
    _id: convertId(albumID),
  };
  AlbumModel.findOneAndUpdate(search, { $inc: { upvotes: 1 } },
    { sort: { upvotes: -1 } }).exec(callback);
  return AlbumModel.find().sort({ upvotes: -1 });
};

AlbumSchema.statics.deleteAlbum = (albumID, callback) => {
  const search = {
    _id: convertId(albumID),
  };

  AlbumModel.deleteOne(search, (err) => {
    if (err) throw err;
  }).exec(callback);
};


AlbumModel = mongoose.model('Album', AlbumSchema);

module.exports.AlbumModel = AlbumModel;
module.exports.AlbumSchema = AlbumSchema;
