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/customWebcams/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 customWebcam");
    });
  }

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

  const data = fs.readFileSync("./apiHandler/customWebcams/webcams.json");
  const webcams = JSON.parse(data);
  
  for (var i in webcams.cams) {
    var q =
      "INSERT INTO customWebcams (name, source_id, loc, protocol_id, link) VALUES (?, ?, POINT(?,?), ?, ?)" 
      con.query(q, [webcams.cams[i].title, getModuleMeta().exactName, webcams.cams[i].loc.lat, webcams.cams[i].loc.lng, webcams.cams[i].embedType, webcams.cams[i].url], function (err, result) {
        tools.handleMysqlErrors(err, getModuleMeta().title);
      });
  }

  console.log("[" + getModuleMeta().title + "] Done");
}

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 customWebcams \
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);
        }
        let results = [];
        for (let e = 0; e < rows.length; e++) {
          const currentRow = rows[e];
          let ty = "";
          if (currentRow.protocol_id == "IFRAME") {
            ty = "webcam-iframe";
          } else if (currentRow.protocol_id == "IMAGE") {
            ty = "webcam-image";
          }
          element = {
            type: ty,
            source: "customWebcam",
            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];
        let ty = "";
        if (currentRow.protocol_id == "IFRAME") {
          ty = "webcam-iframe";
        } else if (currentRow.protocol_id == "IMAGE") {
          ty = "webcam-image";
        }
        element = {
          type: ty,
          source: "customWebcam",
          titel: currentRow.name,
          description: "A web cam read from a file",
          url: currentRow.link,
          uid: currentRow.source_id + "_" + currentRow.id,
          location: {
            lat: currentRow.loc_lat,
            lng: currentRow.loc_lng,
          },
          icon: "cctvIcon",
        };
        results.push(element);
      }
      resolve(results);
    });
  });
}

function getModuleMeta() {
  return {
    title: "custom webcams",
    exactName: "customWebcams",
    country: ["*"],
    tags: ["webcam"],
    limited: false,
  };
}

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