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/ttnantennas/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 ttnantenna");
    });
  }
  const ttnGateways =
    "https://www.thethingsnetwork.org/gateway-data/";
  const mysqlQuery =
    "INSERT INTO ttnantenna (name, description, source_id, loc, protocol_id, link) VALUES (?, ?, ?, POINT(?, ?), ?, ?)";
  const ttnGateRequest =  bent(ttnGateways, "GET", "json", 200);
  ttnGateRequest().then(function(body){
    console.log("[TheThingsnetwork Gateways] Request done");
    let i = 0;
    for (const key in body) {
      const elm = body[key];
      if (elm.location != undefined) {
        if(elm.attributes == undefined){
          elm.attributes = {frequency_plan: "Unknown", placement: "Unknown"}
        }else{
          if(elm.attributes.frequency_plan == undefined){
            elm.attributes.frequency_plan = "Unknown"
          }
          if(elm.attributes.placement == undefined){
            elm.attributes.placement = "Unknown"
          }
        }
        if (
          elm.location.latitude != undefined &&
          elm.location.longitude != undefined
        ) {
          con.query(
            mysqlQuery,
            [
              
              key,
              elm.description +
                "<br>Frequency plan: " +
                elm.attributes.frequency_plan +
                "<br> Altitude: " +
                elm.location.altitude
                + "<br>Placement: " + elm.attributes.placement,
              getModuleMeta().exactName,
              elm.location.latitude,
              elm.location.longitude,
              0,
              "",
            ],
            function (err, result) {
              tools.handleMysqlErrors(err, getModuleMeta().title);
            }
          );
          i++
        }
      }
    }
    console.log("[TheThingsnetwork Gateways] 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.
    var connection = con;

    let elementsToQuery = "*";
    if (minimal) {
      elementsToQuery = "id,loc,source_id";
    }

    const sqlQuery = " \
    SELECT " + elementsToQuery + " \
FROM ttnantenna \
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: "ttnantennas",
          titel: currentRow.name,
          description: currentRow.description,
          url: currentRow.link,
          uid: "ttnantennas_" + currentRow.id,
          location: currentRow.loc,
          icon: "signalIcon"
        };
        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 ttnantenna 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: "ttnantennas",
          titel: currentRow.name,
          description: currentRow.description,
          url: currentRow.link,
          uid: "ttnantennas_" + currentRow.id,
          location: {
            lat: currentRow.loc_lat,
            lng: currentRow.loc_lng,
          },
        };
        results.push(element);
      }
      resolve(results);
    });
  });
}

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

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