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

export const Locations = new Mongo.Collection('locations');

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

Meteor.methods({
    'add.location' (name) {
        check(name, String);

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

        return Locations.insert({
            locationName: name,
            owner: this.userId,
        });
    },
    'edit.location' (locationId, locationName) {
        check(locationId, String);
        check(locationName, String);

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

        return Locations.update({ _id: locationId }, {
            $set: {
                locationName: locationName,
            }
        });
    },
    'delete.location' (locationId) {
        check(locationId, String);

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

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