import { Meteor } from 'meteor/meteor';
import { Mongo } from 'meteor/mongo';
import { check } from 'meteor/check';

export const Categories = new Mongo.Collection('categories');

Categories.allow({
    insert: function(userId, doc){
        // if use id exists, allow insert
        return !!userId;
    },
});

Meteor.methods({
    'add.category' (categoryName) {
        check(categoryName, String);

        if (!this.userId) {
            throw new Meteor.Error('You are not allowed to add categories. Make sure you are logged in with valid user credentials.');
        }

        return Categories.insert({
            categoryName: categoryName,
            categoryOwner: this.userId,
        });
    },
    'edit.category' (categoryId, categoryName,) {
        check(categoryId, String);
        check(categoryName, String);

        if (!this.userId) {
            throw new Meteor.Error('You are not allowed to edit categories. Make sure you are logged in with valid user credentials.');
        }

        return Categories.update({ _id: categoryId }, {
            $set: {
                categoryName: categoryName,
            }
        });
    },
    'delete.category' (categoryId) {
        check(categoryId, String);

        if (!this.userId) {
            throw new Meteor.Error('You are not allowed to delete categories. Make sure you are logged in with valid user credentials.');
        }

        let categoryInfo = Categories.findOne({ _id: categoryId });
        let myId = this.userId;
        if (myId == categoryInfo.owner) {
            return Categories.remove({ _id: categoryId });
        } else {
            console.log("User not allowed to delete this Category. Not the owner!");
            return("Not Allowed!");
        }
    },
});