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

let con = undefined;

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

  for (i in array) {
    con.query(array[i], function (err, result) {
      if (err) throw err;
      console.log("Table created for ttncomms");
    });
  }
  const ttnCommUrl =
    "https://www.thethingsnetwork.org/community.json";
  const mysqlQuery =
    "INSERT INTO ttncomms (name, description, source_id, loc, protocol_id, link) VALUES (?, ?, ?, POINT(?, ?), ?, ?)";
  const res = bent(ttnCommUrl, 'GET', 'json', 200);

  res().then(function(body){
    console.log("[TheThingsnetwork Communities] Request done");
    for (let c = 0; c < body.length; c++) {
      const elm = body[c];
      if (elm.lat != null && elm.lon != null) {
        con.query(
          mysqlQuery,
          [
            "TTN Community " + elm.title,
            "",
            getModuleMeta().exactName,
            elm.lat,
            elm.lon,
            0,
            "https://www.thethingsnetwork.org" + elm.path,
          ],
          function (err, result) {
            if (err) {
              throw err;
            }
          }
        );
      }
    }
    console.log("[TheThingsnetwork Communities] Insert into Database done!");
  }, function(err){
    console.warn("[" + getModuleMeta().title + "] Was unable to resolve request with error: " + err)
  });
}

function queryData(boundNorthEastLatLng, boundSouthWestLatLng, minimal) {
  // Create a new promise to return, DBs are slow.
  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 airspy \
 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: "ttncomms",
          titel: currentRow.name,
          description: "This is a TheThingsnetwork Comunity. URL: " + currentRow.link,
          url: currentRow.link,
          uid: "ttncomms_" + currentRow.id,
          location: currentRow.loc,
        };
        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("_");
  console.log("[ttncomms] Query item with uid: " + uid + " using id: " + parseInt(uidParts[1]));

  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("[ttncomms] Query done, result: " + rows);
    let results = [];
    if(rows.length > 0){
      
      for (let e = 0; e < rows.length; e++) {
        const currentRow = rows[e];
        const element = {
          type: "general-poi",
          source: "ttncomms",
          titel: currentRow.name,
          description: "This is a TheThingsnetwork Comunity. URL: " + currentRow.link,
          url: currentRow.link,
          uid: "ttncomms_" + currentRow.id,
          location: {
            lat: currentRow.loc_lat,
            lng: currentRow.loc_lng,
          },
        };
        results.push(element);
      }

    }/*else{
      results = [{
        type: "general-poi",
        source: "ttncomms",
        titel: "Invalid",
        description: "This is broken. Something is broken.",
        url: "INVALID",
        uid: uid,
        location: {
          lat: 0,
          lng: 0,
        },
      }];
    }*/
    
    resolve(results)
  });
});
}

function getModuleMeta() {
  return {
    title: "TheThingsnetwork Communities",
    exactName: "ttncomms",
    country: ["*"],
    limited: false,
  };
}

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