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

let con = undefined;

function initialize(connection) {
  con = connection;
  var array = fs
    .readFileSync("./apiHandler/autobahn/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 autobahn");
    });
  }

  const roadURL = "https://verkehr.autobahn.de/o/autobahn/";
  const baseURL = "https://verkehr.autobahn.de/o/autobahn/#/services/webcam";

  var hws = [];
  var index_count_cams = 0;

  console.log(
    "[" +
      getModuleMeta().title +
      "] Starting requests"
  );

  const roadRequest = bent(roadURL, "GET", "json", 200);
  roadRequest().then(
    function (body) {
      hws = body.roads;

      for (h in hws) {
        if (!hws[h].includes("/")) {
          let camRequest = bent(
            baseURL.replace("#", hws[h]),
            "GET",
            "json",
            200
          );
          camRequest().then(
            function (body) {
              for (var i in body.webcam) {
                var q =
                  "INSERT INTO autobahn (name, source_id, loc, protocol_id, link) VALUES (?, ?, POINT(?, ?), 0, ?)"
                if (body.webcam[i].linkurl != "") {
                  index_count_cams += 1;
                  con.query(q, [body.webcam[i].title, getModuleMeta().exactName, body.webcam[i].coordinate.lat, body.webcam[i].coordinate.long, body.webcam[i].linkurl], function (err, result) {
                    tools.handleMysqlErrors(err, getModuleMeta().title);
                  });
                }
              }
            },
            function (err) {
              console.warn(
                "[" +
                  getModuleMeta().title +
                  "] Was unable to resolve request with error: " +
                  err
              );
            }
          );
        }
      }
    },
    function (err) {
      console.warn(
        "[" +
          getModuleMeta().title +
          "] Was unable to resolve request with error: " +
          err
      );
    }
  );
  console.log(
    "[" +
      getModuleMeta().title +
      "] Done"
  );
}

function queryData(boundNorthEastLatLng, boundSouthWestLatLng, 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.
    var connection = con;

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

    const sqlQuery = " \
    SELECT " + elementsToQuery + " \
FROM autobahn \
WHERE MBRContains( \
  GeomFromText( 'LINESTRING(? ?,? ?)' ), \
  loc)";

    connection.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);
        }
        let results = [];
        for (let e = 0; e < rows.length; e++) {
          const currentRow = rows[e];
          element = {
            type: "webcam-iframe",
            source: "Autobahn",
            titel: currentRow.name,
            description: "An example webcam with a url",
            url: currentRow.link,
            uid: currentRow.source_id + "_" + currentRow.id,
            location: currentRow.loc,
            icon: "cctvIcon",
          };

          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: "webcam-iframe",
          source: "Autobahn",
          titel: currentRow.name,
          description: "An example webcam with a url",
          url: currentRow.link,
          uid: currentRow.source_id + "_" + currentRow.id,
          location: currentRow.loc,
          icon: "cctvIcon",
        };
        results.push(element);
      }
      resolve(results);
    });
  });
}

function getModuleMeta() {
  return {
    title: "Autobahn",
    exactName: "autobahn",
    country: ["DEU"],
    tags: ["webcam"],
    limited: false,
  };
}

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