/*
2 Permissions : admin, user

user: GET category, geolocation, own profile, number of users
      UPDATE own profile
      POST geolocation

admin: GET all
       POST all
       UPDATE all
       DELETE all
*/

module.exports = function(app) {
    var Role = app.models.Role;

    Role.registerResolver('admin', function(role, context, cb) {
        function reject() {
          process.nextTick(function() {
            cb(null, false);
          });
        }
    

        switch (context.modelName){
            case 'end_user':
                break;
            case 'geolocation':
                break;
            case 'category':
                break;
            default:
                return reject();
        }

        // // if the target model is not project
        // if (context.modelName !== 'project') {
        //   return reject();
        // }
    
        // do not allow anonymous users
        var userId = context.accessToken.userId;
        if (!userId) {
          return reject();
        }
    
        // check if userId is in team table for the given project id
        context.model.findById(context.modelId, function(err, model) {
            if (err || !model)
                return reject();
        
            var EndUser = app.models.EndUser;
            EndUser.count({
                ownerId: model.ownerId,
                memberId: userId
            }, function(err, count) {
                if (err) {
                    console.log(err);
                    return cb(null, false);
                }
        
                cb(null, count > 0); // true = is a team member
            });
        });
    });


    Role.registerResolver('user', function(role, context, cb) {
      function reject() {
        process.nextTick(function() {
          cb(null, false);
        });
      }
  
      switch (context.modelName){
        case 'end_user':
            break;
        case 'geolocation':
            break;
        case 'category':
            break;
        default:
            return reject();
        }

        // // if the target model is not project
        // if (context.modelName !== 'project') {
        //   return reject();
        // }

        // do not allow anonymous users
        var userId = context.accessToken.userId;
        if (!userId) {
        return reject();
        }

        // check if userId is in team table for the given project id
        context.model.findById(context.modelId, function(err, model) {
            if (err || !model)
                return reject();

            var EndUser = app.models.EndUser;
            EndUser.count({
                ownerId: model.ownerId,
                memberId: userId
            }, function(err, count) {
                if (err) {
                    console.log(err);
                    return cb(null, false);
                }

                cb(null, count > 0); // true = is a team member
            });
        });
    });
  };