import $ from 'jquery';

class SeismicControl {
  constructor(arrayVisualization, subarrayDisplay) {
    this.visualization = arrayVisualization;
    this.subarrayDisplay = subarrayDisplay;
  }

  init(seismicSelector, bannerSelector) {
    let self = this;

    seismicSelector.find("#add_seismic").click(function () {
      self.visualization.addSeismicAnchor();
    });

    seismicSelector.find("#remove_seismic").click(function () {
      self.visualization.removeSeismicAnchor();
    });

    seismicSelector.find("#save_seismic_changes").click(function () {
      let updatedData = self.visualization.panelData.map((panel) => {
        return {
          panel_id: panel.data.panel_id,
          seismic_anchors: panel.data.seismic_anchors
        };
      });

      $.ajax({
        url: "/api/update_panel_data",
        data: JSON.stringify(updatedData),
        contentType: "application/json; charset=utf-8",
        method: 'POST'
      })
        .then(function (data) {
          bannerSelector.removeClass("seismic_error");
          bannerSelector.removeClass("seismic_success");
          bannerSelector.removeClass("hidden");

          let seismicClass;
          let bannerText;

          bannerSelector.find(".circle").removeClass("icon-ok");
          bannerSelector.find(".circle").text("!");
          if (data.status !== undefined && data.status == "success") {
            seismicClass = "seismic_success";
            bannerText = "Changes to the Seismic Anchors have been successfully saved!";
            bannerSelector.find(".circle").addClass("icon-ok");
            bannerSelector.find(".circle").text("");
            self.visualization.refreshPanels(data.panel_data);
            self.subarrayDisplay.didUpdateSubarrayData(data.subarray_data);
          } else if (data.error !== undefined) {
            seismicClass = "seismic_error";
            bannerText = data.error;
            self.subarrayDisplay.didUpdateSubarrayData(data.subarray_data);
          } else {
            seismicClass = "seismic_error";
            bannerText = "Unknown error, please try again.";
          }

          bannerSelector.addClass(seismicClass);
          bannerSelector.find(".seismic_save_message").text(bannerText);
        });
    });

    bannerSelector.find(".dismiss_button").click(function () {
      bannerSelector.addClass("hidden");
      bannerSelector.removeClass("seismic_error");
      bannerSelector.removeClass("seismic_success");
    });
  }
}

export default SeismicControl;