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

export const ShopLists = new Mongo.Collection('shoplists');

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

Meteor.methods({
    'add.shopList' (shopName) {
        check(shopName, Sring);

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

        return ShopLists.insert({
            shopName: shopName,
            shopOwner: this.userId,
        });
    },
    'edit.shopList' (shopId, shopName) {
        check(shopId, String);
        check(shopName, String);

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

        return ShopLists.update({ _id: shopId }, {
            $set: {
                shopName: shopName,
            }
        });
    },
    'delete.shopList' (shopId) {
        check(shopId, String);

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

        return ShopLists.remove({ _id: shopId });
    },
});