/*
    Helper methods for use in the other modules.
*/
const fs = require('fs');

module.exports.formatResponse = function (obj, req, res) {
    res.header("Content-Type", 'application/json');

    if (req.query && req.query.f && req.query.f == 'pjson')
        res.send(JSON.stringify(obj, null, 4));
    else
        res.send(obj);
}

module.exports.loadJSON = function (filename) {
  let rawdata = fs.readFileSync(filename);
  let jsondata = JSON.parse(rawdata);

  return jsondata;
}

module.exports.getCentroid = function (geometry) {
  let firstPoint = geometry.coordinates[0][0]

  if (firstPoint.length > 2)
    firstPoint = firstPoint[0];

  let xmin = firstPoint[0];
  let xmax = firstPoint[0];
  let ymin = firstPoint[1];
  let ymax = firstPoint[1];

  geometry.coordinates[0].forEach(pt => {
    if (pt[0] < xmin) xmin = pt[0];
    if (pt[0] > xmax) xmax = pt[0];
    if (pt[1] < ymin) ymin = pt[1];
    if (pt[1] > ymax) ymax = pt[1];
  });

  return [(ymin + ymax) / 2.0, (xmin + xmax) / 2.0];
}

module.exports.getPilotRegion = function (nuts, pilots) {
  for (let i = 0; i < pilots.length; i++) {
    if (nuts.startsWith(pilots[i].nuts))
      return pilots[i];
  }

  return null;
}