const fs = require("fs");
const mysql = require("mysql");
const bent = require('bent')
const tools = require("../../functions");

let con = undefined;

function initialize(conection) {
  con = conection;
  const filePath =
    "./apiHandler/" + getModuleMeta().exactName + "/db_table_config.sql";
  const array = fs.readFileSync(filePath).toString().split("\n");

  for (i in array) {
    con.query(array[i], function (err, result) {
      if (err) throw err;
      console.log("Table created for " + getModuleMeta().title);
    });
  }

  const requestURL = "https://api.opensensemap.org/boxes";
  const mysqlQuery =
    "INSERT INTO opensensemap (name, description, source_id, loc, protocol_id, link) VALUES (?, ?, ?, POINT(?, ?), ?, ?)";
  const res = bent(requestURL, 'GET', 'json', 200);
  res().then(function(response){
    body = response
    console.log("[" + getModuleMeta().title + "] Request done");
    for (let c = 0; c < body.length; c++) {
      const elm = body[c];
      con.query(
        mysqlQuery,
        [
          elm.name,
          "",
          getModuleMeta().exactName,
          elm.currentLocation.coordinates[1],
          elm.currentLocation.coordinates[0],
          0,
          "https://sensebox.github.io/opensensemap-widget/iframe.html?senseboxId=" + elm._id,
        ],
        function (err, result) {
          tools.handleMysqlErrors(err, getModuleMeta().title);
        }
      );
    }
    console.log("[" + getModuleMeta().title + "] Insert into Database done!");
  }, function(err){
    console.warn("[" + getModuleMeta().title + "] Was unable to resolve request with error: " + err)
  });
}

function queryData(boundNorthEastLatLng, boundSouthWestLatLng, minimal) {
  return new Promise(function (resolve, reject) {
    // The Promise constructor should catch any errors thrown on
    // this tick. Alternately, try/catch and reject(err) on catch.
    let elementsToQuery = "*";
    if (minimal) {
      elementsToQuery = "id,loc,source_id";
    }
    // This is taken from https://stackoverflow.com/questions/21208697/select-all-geospatial-points-inside-a-bounding-box
    const sqlQuery = " \
          SELECT " + elementsToQuery + " \
  FROM opensensemap \
 WHERE MBRContains( \
        GeomFromText( 'LINESTRING(? ?,? ?)' ), \
        loc)";

    con.query(sqlQuery, [boundNorthEastLatLng.lat, boundNorthEastLatLng.lng, boundSouthWestLatLng.lat, boundSouthWestLatLng.lng], function (err, rows, fields) {
      // Call reject on error states,
      // call resolve with results
      if (err) {
        return reject(err);
      }

      const results = [];
      for (let e = 0; e < rows.length; e++) {
        const currentRow = rows[e];
        const element = {
          type: "iframe",
          source: getModuleMeta().exactName,
          titel: currentRow.name,
          description: "",
          url: currentRow.link,
          uid: "opensensemap_" + currentRow.id,
          location: currentRow.loc,
          icon: "temperatureIcon"
        };
        if (minimal) {
          const stripableElements = ["title", "description", "url", "type"];
          for (h in stripableElements) {
            delete element[stripableElements[h]];
          }
        }

        results.push(element);
      }
      resolve(results);
    });
  });
}

function queryItem(uid){
  const uidParts = uid.split("_");

  const sqlQuery = "SELECT * FROM `" + getModuleMeta().exactName + "` WHERE id=?"
  return new Promise(function (resolve, reject) {
  con.query(sqlQuery, [parseInt(uidParts[1])], function (err, rows, fields) {
    if (err) {
      return reject(err);
    }
    console.log()
    const results = [];
    for (let e = 0; e < rows.length; e++) {
      const currentRow = rows[e];
      const element = {
        type: "iframe",
        source: getModuleMeta().exactName,
        titel: currentRow.name,
        description: "",
        url: currentRow.link,
        uid: "opensensemap_" + currentRow.id,
        distance: tools.roundOff(currentRow.distance, 4),
        location: currentRow.loc,
        icon: "temperatureIcon"
      };
      results.push(element);
    }
    resolve(results)
  });
});
}



function getModuleMeta() {
  return {
    title: "OpenSensemap",
    exactName: "opensensemap",
    tags: ["temperature", "envoriment"],
    country: ["*"],
    limited: false,
  };
}

module.exports = { initialize, queryData, getModuleMeta, queryItem };
