import schema from './schema.js';
import { createCollection, getDefaultResolvers, getDefaultMutations } from 'meteor/vulcan:core';
import Users from 'meteor/vulcan:users';
import { addUniversalFields } from '../../collectionUtils'

const options = {
  newCheck: (user) => {
    if (!user) return false;
    return Users.canDo(user, 'posts.new')
  },

  editCheck: (user, document) => {
    if (!user || !document) return false;
    if (Users.canDo(user, 'posts.alignment.move.all') ||
        Users.canDo(user, 'posts.alignment.suggest')) {
      return true
    }
    return Users.owns(user, document) ? Users.canDo(user, 'posts.edit.own') : Users.canDo(user, `posts.edit.all`)
  },

  removeCheck: (user, document) => {
    if (!user || !document) return false;
    return Users.owns(user, document) ? Users.canDo(user, 'posts.edit.own') : Users.canDo(user, `posts.edit.all`)
  },
}

export const Posts = createCollection({
  collectionName: 'Posts',
  typeName: 'Post',
  schema,
  resolvers: getDefaultResolvers('Posts'),
  mutations: getDefaultMutations('Posts', options),
});

// refactor: moved here from schema.js
Posts.config = {};

Posts.config.STATUS_PENDING = 1;
Posts.config.STATUS_APPROVED = 2;
Posts.config.STATUS_REJECTED = 3;
Posts.config.STATUS_SPAM = 4;
Posts.config.STATUS_DELETED = 5;


// Post statuses
Posts.statuses = [
  {
    value: 1,
    label: 'pending'
  },
  {
    value: 2,
    label: 'approved'
  },
  {
    value: 3,
    label: 'rejected'
  },
  {
    value: 4,
    label: 'spam'
  },
  {
    value: 5,
    label: 'deleted'
  }
];

Posts.checkAccess = (currentUser, post) => {
  if (Users.isAdmin(currentUser) || Users.owns(currentUser, post)) { // admins can always see everything, users can always see their own posts
    return true;
  } else if (post.isFuture) {
    return false;
  } else {
    const status = _.findWhere(Posts.statuses, {value: post.status});
    return Users.canDo(currentUser, `posts.view.${status.label}`);
  }
}

addUniversalFields({collection: Posts})

export default Posts;
@@ -1563,416 +1563,8 @@
 %5D;%0A%0A
-Posts.checkAccess = (currentUser, post) =%3E %7B%0A  if (Users.isAdmin(currentUser) %7C%7C Users.owns(currentUser, post)) %7B // admins can always see everything, users can always see their own posts%0A    return true;%0A  %7D else if (post.isFuture) %7B%0A    return false;%0A  %7D else %7B%0A    const status = _.findWhere(Posts.statuses, %7Bvalue: post.status%7D);%0A    return Users.canDo(currentUser, %60posts.view.$%7Bstatus.label%7D%60);%0A  %7D%0A%7D%0A%0A
 addU

Remove a duplicate Posts.checkAccess function