class SubarrayDisplay {
  init(currentSeismicCountSelector, neededAnchorSelector, weightSelector, panelData) {
    this.currentSeismicCountSelector = currentSeismicCountSelector;
    this.neededAnchorSelector = neededAnchorSelector;
    this.weightSelector = weightSelector;
    this.didModifyPanels(panelData);
  }

  didModifyPanels(panelData) {
    let seismicCount = this.computeSeismicAnchorCounts(panelData);

    this.assignSeismicCountItems(seismicCount);
  }

  didUpdateSubarrayData(subarrayData) {
    for (let i = 0; i < subarrayData.length; i++) {
      let data = subarrayData[i];
      let subarray = i + 2;
      let neededAnchors = data.required_seismic_anchors;
      let weight = data.weight;
      this.neededAnchorSelector.find('td:nth-child(' + subarray + ')').text(neededAnchors);
      this.weightSelector.find('td:nth-child(' + subarray + ')').text(weight.toLocaleString());
    }
  }

  computeSeismicAnchorCounts(panelData) {
    let seismicCount = {};
    for (let i = 0; i < panelData.length; i++) {
      let panel = panelData[i].data;
      if (seismicCount[panel.subarray] === undefined) {
        seismicCount[panel.subarray] = 0;
      }
      seismicCount[panel.subarray] += panel.seismic_anchors;
    }

    return seismicCount
  }

  assignSeismicCountItems(seismicAnchorCounts) {
    for (var subarray in seismicAnchorCounts) {
      if (seismicAnchorCounts.hasOwnProperty(subarray)) {
        const childId = parseInt(Object.keys(seismicAnchorCounts).indexOf(subarray)) + 2;
        this.currentSeismicCountSelector.find(`td:nth-child(${childId})`).text(seismicAnchorCounts[subarray]);
      }
    }
  }
}

export default SubarrayDisplay;
