import {Meteor} from "meteor/meteor";
import {Roles} from "meteor/alanning:roles";
import {LocationsDB, LocationValues} from "/imports/api/Listings/both/collections/locations";

Meteor.methods({

    "locations.get"(locationId: string) {
        if(!this.userId || !Roles.userIsInRole(this.userId, 'admin', Roles.GLOBAL_GROUP)) {
            throw new Meteor.Error("not-allowed");
        }

        return LocationsDB.findOne({ _id: locationId });
    },

    "locations.create"(locationValues: LocationValues) {
        if(!this.userId || !Roles.userIsInRole(this.userId, 'admin', Roles.GLOBAL_GROUP)) {
            throw new Meteor.Error("not-allowed");
        }

        return LocationsDB.insert({...locationValues, isLanding: false, isPublic: false});
    },

    "locations.toggleIsPublic"(locationId: string) {
        if(!this.userId || !Roles.userIsInRole(this.userId, 'admin', Roles.GLOBAL_GROUP)) {
            throw new Meteor.Error("not-allowed");
        }

        const location = LocationsDB.findOne({ _id: locationId });
        if(location) {
            LocationsDB.update({ _id: locationId }, { $set: { isPublic: !location.isPublic } });
        }
    },

    "locations.toggleIsLanding"(locationId: string) {
        if(!this.userId || !Roles.userIsInRole(this.userId, 'admin', Roles.GLOBAL_GROUP)) {
            throw new Meteor.Error("not-allowed");
        }

        const location = LocationsDB.findOne({ _id: locationId });
        if(location) {
            LocationsDB.update({ _id: locationId }, { $set: { isLanding: !location.isLanding } });
        }
    },

    "locations.update"(locationId: string, locationValues: LocationValues) {
        if(!this.userId || !Roles.userIsInRole(this.userId, 'admin', Roles.GLOBAL_GROUP)) {
            throw new Meteor.Error("not-allowed");
        }

        return LocationsDB.update({ _id: locationId }, { $set: locationValues });
    },

    "locations.delete"(locationId: string) {
        if(!this.userId || !Roles.userIsInRole(this.userId, 'admin', Roles.GLOBAL_GROUP)) {
            throw new Meteor.Error("not-allowed");
        }

        return LocationsDB.remove({ _id: locationId });
    }

});