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

export const RecipeItems = new Mongo.Collection('recipeitems');

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

Meteor.methods({
    'add.recipeItem' (recipeId, recipeItemType, recipeItem) {
        check(recipeId, String);
        check(recipeItemType, String);
        check(recipeItem, String);

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

        return RecipeItems.insert({
            recipeId: recipeId,
            recipeItemType: recipeItemType,
            recipeItem: recipeItem,
        });
    },
    'edit.recipeItem' (recipeItemId, recipeId, recipeItemType, recipeItem) {
        check(recipeItemId, String);
        check(recipeId, String);
        check(recipeItemType, String);
        check(recipeItem, String);

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

        return RecipeItems.update({ _id: recipeItemId }, {
            $set: {
                recipeId: recipeId,
                recipeItemType: recipeItemType,
                recipeItem: recipeItem,
            }
        });
    },
    'delete.recipeItem' (recipeItemId) {
        check(recipeItemId, String);

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

        return RecipeItems.remove({ _id: recipeItemId });
    }
});