import models from "../models";

class Stations {
  /**
   * Méthode permettant de récuper la liste des stations selon des critères
   * @param {Object} req
   * @param {Function} callback
   */
  static getAll(req, callback) {
    const { radius, lon, lat, start, limit } = req.query;

    if (!lon || !lat) {
      callback(new Error("Missing lat, lon or radius"));
    } else {
      const query = {
        location: {
          $near: {
            $maxDistance: Number(radius),
            $geometry: {
              type: "Point",
              coordinates: [Number(lon), Number(lat)]
            }
          }
        }
      };

      const skip = parseInt(start || 0, 10);
      const _limit = parseInt(limit && limit <= 50 ? limit : 20, 10);

      models.Stations.count(query)
        .then(count => {
          models.Stations.find(query)
            .skip(skip)
            .limit(_limit)
            .then(items => {
              callback(null, { total: count, items });
            });
        })
        .catch(callback);
    }
  }
}

export default Stations;
