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

let con = undefined;

function initialize(connection) {
  con = connection;
  const array = fs
    .readFileSync("./apiHandler/freifunk/db_table_config.sql")
    .toString()
    .split("\n");

  for (i in array) {
    con.query(array[i], function (err, result) {
      tools.handleMysqlErrors(err, getModuleMeta().title);
      console.log("Table created for freifunk");
    });
  }
  const freifunkDataUrl = "https://www.freifunk-karte.de/data.php";
  const mysqlQuery =
    "INSERT INTO freifunk (name, description, source_id, loc, protocol_id, link) VALUES (?, ?, ?, POINT(?, ?), ?, ?)";
  const resulter = bent(freifunkDataUrl, 'GET', 'json', 200);
  resulter().then(function(body){
    console.log("[Freifunk] Request done");
    for (let c = 0; c < body.allTheRouters.length; c++) {
      const elm = body.allTheRouters[c];
      con.query(
        mysqlQuery,
        [
          elm.name,
          elm.community,
          getModuleMeta().exactName,
          elm.lat,
          elm.long,
          0,
          "https://www.freifunk-karte.de/",
        ],
        function (err, result) {
          tools.handleMysqlErrors(err, getModuleMeta().title);
        }
      );
    }
    console.log("[Freifunk] 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";
    }
    const sqlQuery = " \
    SELECT " + elementsToQuery + " \
FROM freifunk \
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: "general-poi",
          source: "Freifunk",
          titel: currentRow.name,
          description:
            "This is an AP by the " +
            currentRow.description +
            " Freifunk Comunity",
          url: currentRow.link,
          uid: "freifunk_" + currentRow.id,
          location: currentRow.loc,
          icon: "wifiIcon"
        };

        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);
    }
    const results = [];
    for (let e = 0; e < rows.length; e++) {
      const currentRow = rows[e];
      const element = {
        type: "general-poi",
        source: "Freifunk",
        titel: currentRow.name,
        description:
          "This is an AP by the " +
          currentRow.description +
          " Freifunk Comunity",
        url: currentRow.link,
        uid: "freifunk_" + currentRow.id,
        location: currentRow.loc,
        icon: "wifiIcon"
      };
      results.push(element);
    }
    resolve(results)
  });
});
}

function getModuleMeta() {
  return {
    title: "Freifunk",
    exactName: "freifunk",
    country: ["*"],
    tags: ["AP"],
    limited: false,
  };
}

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