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

let con = undefined;

function initialize(conection) {
  con = conection;
  // Prepare all of the tables needed
  const array = fs
    .readFileSync("./apiHandler/airspydirectory/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 AirspyDirectory");
    });
  }

  const airspyDirectoryApiUrl = "https://airspy.com/directory/status.json";
  const mysqlQuery =
    "INSERT INTO airspy (name, description, loc, source_id, protocol_id, link) VALUES ( ?, ?, POINT(?,?), ?, ?, ?)";

  // Request API and save into table
  const request = bent(airspyDirectoryApiUrl, "GET", "json", 200);
  request().then(function(body){
    console.log("[AirSpyDirectory] Request done");
    for (let c = 0; c < body.servers.length; c++) {
      const elm = body.servers[c];
      con.query(
        mysqlQuery,
        [
          elm.deviceType,
          elm.generalDescription +
            "<br> Adress: " +
            elm.streamingHost +
            ":" +
            elm.streamingPort +
            "<br>" +
            "Owned by: " +
            elm.ownerName,
          elm.antennaLocation.lat,
           elm.antennaLocation.long,
          0,
          0,
          "https://airspy.com/directory/status.json",
        ],
        function (err, result) {
          tools.handleMysqlErrors(err, getModuleMeta().title);
        }
      );
    }
    console.log("[AirSpyDirectory] 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); // Probably bad for PROD
      }

      const results = [];
      for (let e = 0; e < rows.length; e++) {
        const currentRow = rows[e];
        let element = {
          type: "general-poi",
          source: "AirSpyDirectory",
          titel: currentRow.name,
          description: currentRow.description,
          url: currentRow.link,
          uid: "airspydirectory_" + 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 airspy 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: "AirSpyDirectory",
          titel: currentRow.name,
          description: currentRow.description,
          url: currentRow.link,
          uid: "airspydirectory_" + currentRow.id,
          location: currentRow.loc,
          icon: "signalIcon",
        };
        results.push(element);
      }
      resolve(results);
    });
  });
}

function getModuleMeta() {
  return {
    title: "AirSpyDirectory",
    exactName: "airspydirectory",
    country: ["*"],
    tags: ["RF"],
    features: ["tags"],
    limited: false,
  };
}

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