
var BasicStrategy = require('passport-http').BasicStrategy;

var akasha, config;

module.exports.config = function(_akasha, _config) {
	akasha = _akasha;
	config = _config;
};

var findById = function(id, done) {
	if (config.editor && config.editor.users) {
		var user;
		for (var i in config.editor.users) {
			if (config.editor.users[i].id === id) {
				user = config.editor.users[i];
				break;
			}
		}
		done(undefined, user);
	} else done();
};

var findByUsername = function(username, done) {
	if (config.editor && config.editor.users) {
		var user;
		for (var i in config.editor.users) {
			if (config.editor.users[i].name === username) {
				user = config.editor.users[i];
				break;
			}
		}
		done(undefined, user);
	} else done();
};

module.exports.serialize = function(user, done) {
  done(null, user.id);
}

module.exports.deserialize = function(id, done) {
  findById(id, function (err, user) {
    done(err, user);
  });
}

module.exports.strategy = new BasicStrategy(
  function(username, password, done) {
    findByUsername(username, function (err, user) {
      if (err) { return done(err); }
      if (!user) { return done(null, false); }
      if (!user.password === password) { return done(null, false); }
      return done(null, user);
    });
  }
)



/* new DigestStrategy({ qop: 'auth' },
  function(username, done) {
    // Find the user by username.  If there is no user with the given username
    // set the user to `false` to indicate failure.  Otherwise, return the
    // user and user's password.
    findByUsername(username, function(err, user) {
      if (err) { return done(err); }
      if (!user) { return done(null, false); }
      return done(null, user, user.password);
    })
  },
  function(params, done) {
    // asynchronous validation, for effect...
    process.nextTick(function () {
      // check nonces in params here, if desired
      return done(null, true);
    });
  }
); */


/*new LocalStrategy(
  function(username, password, done) {
    process.nextTick(function () {
      // Find the user by username. If there is no user with the given
      // username, or the password is not correct, set the user to `false` to
      // indicate failure and set a flash message. Otherwise, return the
      // authenticated `user`.
      findByUsername(username, function(err, user) {
        if (err) { return done(err); }
        if (!user) { return done(null, false, { message: 'Unknown user ' + username }); }
        if (user.password !== password) { return done(null, false, { message: 'Invalid password' }); }
        return done(null, user);
      })
    });
  }
); */
