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

let con = undefined;

function initialize(conection) {
  console.error("!! THE EXAMPLE MODULE HAS BEEN ENABLED, NEVER ENABLE TO EXAMPLE MODULE !!")
  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://example.com/api.json";
  const mysqlQuery = "INSERT INTO " + getModuleMeta().exactName + " (" + getModuleMeta().exactName + "_id, " + getModuleMeta().exactName + "_name, " + getModuleMeta().exactName + "_description, source_id, " + getModuleMeta().exactName + "_loc_lat, " + getModuleMeta().exactName + "_loc_lng, " + getModuleMeta().exactName + "_protocol_id, " + getModuleMeta().exactName + "_link) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";

  request(requestURL, { json: true }, (err, res2, body) => {
    if (err) {
      throw err;
    }
    console.log("[" + getModuleMeta().title + "] Request done")
    for (let c = 0; c < body.length; c++) {

      const elm = body[c];
      con.query(mysqlQuery, [c, elm.name, "", 0, elm.currentLocation.coordinates[1], elm.currentLocation.coordinates[0], 0, "https://api.opensensemap.org/boxes/" + elm._id], function (err, result) {
        if (err) { throw (err) }
      })
    }
    console.log("[" + getModuleMeta().title + "] Insert into Database done!")
  });
}

function queryData(lat, lng, radius, minimal) {
  /*
  radius in km

  */

  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_lat,loc_lng,source_id";
    }

    const sqlQuery =
      "SELECT \
    " +
      elementsToQuery +
      ", \
  ( 6371 \
    * acos( cos( radians(?) ) \
            * cos(  radians( " + getModuleMeta().exactName + "_loc_lat )   ) \
            * cos(  radians( " + getModuleMeta().exactName + "_loc_lng ) - radians(?) ) \
          + sin( radians(?) ) \
            * sin( radians( " + getModuleMeta().exactName + "_loc_lat ) ) \
          ) \
  ) \
  AS distance \
FROM " + getModuleMeta().exactName + " \
HAVING distance < ? \
ORDER BY distance";

    con.query(sqlQuery, [lat, lng, lat, radius], 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": "request-info",
          "source": getModuleMeta().title,
          "titel": currentRow.example_name,
          "description": "",
          "url": currentRow.example_link,
          "distance": currentRow.distance,
          "location": {
            "lat": currentRow.example_loc_lat,
            "lng": currentRow.example_loc_lng
          }
        }
        results.push(element)
      }
      resolve(results);
    });
  });
}

function getModuleMeta() {
  return {
    title: "Example",
    exactName: "example",
    country: ["*"],
    limited: false,
  };
}

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