define([
  "dojo/_base/declare",
  "dojo/request",
  "helpers/UrlBuilder",
  "CesiumAdaptor/CesiumViewer",
  "helpers/Layers",
  "helpers/RequestWrapper",
  "dojo/topic"
], function (declare, request, UrlBuilder, CesiumViewer, Layers, RequestWrapper, topic) {

  return declare(null, {

    constructor: function () {
      this._layers = null;
      this._active_layer = null;
      this._bb = null;

    },

    getLayers: function () {

      let url = new UrlBuilder(location.protocol.slice(0, -1), $("#host").val())
        .port($("#port").val())
        .path($("#endpoint").val())
        .param("service", "3DPS")
        .param("acceptversions", "1.0")
        .param("request", "GetCapabilities")
        .build();

      request(url, { handleAs: "text" }).then(document => {

        this._layers = new Layers(document);

        $("#layersList").empty();

        $.each(this._layers.getLayers(), function (i, layer) {
          $("#layersList").append($("<option>", {
            value: layer.id,
            text: layer.name
          }));
        });

      });


    },

    selectLayer: function (layer) {
      this._active_layer = layer;
      let layerCenter = this._layers.getLayerCenter(layer);
      let viewer = CesiumViewer.getViewer();
      let center = Cesium.Cartesian3.fromDegrees(layerCenter.lon, layerCenter.lat, 20000.0);
      viewer.camera.setView({
        destination: center,
        orientation: {
          heading: 0.0,
          pitch: Cesium.Math.toRadians(-90),
          roll: 0.0
        }
      });
    },

    setBoundingBox: function (bb) {
      this._bb = bb;
    },

    invokeRequest: function () {
      let requestWrapper = new RequestWrapper();
      let req = {
        host: $("#host").val(),
        port: $("#port").val(),
        endpoint: $("#endpoint").val(),
        layer: this._active_layer
      };
      if (this._bb) {
        req.boundingBox = this._bb;
      }
      requestWrapper.request(req);
    },

    clear: function () {
      this._active_layer = null;
      this._bb = null;
    },

    clearBoundingBox: function () {
      this._bb = null;
    },

    showAddTempLayer: function () {
      $('#addTempLayerModal').modal('show');
    },

    addTempLayer: function () {

      let data = {
        name: $("#tempLayerName").val(),
        url: $("#tempLayerUrl").val()
      };

      $("#tempLayerName").val("");
      $("#tempLayerUrl").val("");

      let url = new UrlBuilder(location.protocol.slice(0, -1), $("#host").val())
        .port($("#port").val())
        .path("tempassets")
        .build();

      request.post(url, {
        headers: {
          "Content-Type": "application/json"
        },
        data: JSON.stringify(data),
      }).then(function (message) {
        topic.publish("TempLayerAdded", "TemporaryLayerAdded");
      });

    }

  });

});