import '../../../lib/easeljs.js';
import $ from "jquery";
import {Panel} from './panel';
import Colors from "./colors";

class ArrayVisualization {
  constructor(panelData, isDualTilt, subarrayDisplay, buildings) {
    this.panelData = panelData;
    this.isDualTilt = isDualTilt;
    this.subarrayDisplay = subarrayDisplay;
    this.buildings = buildings;

    // Default options
    this.scale = 10;
    this.panels = [];
  }

  init() {
    this.stage = new createjs.Stage("arrayCanvas");
    this.container = new createjs.Container();

    let background = new createjs.Shape();
    background.graphics.beginFill(Colors.canvas_background).drawRect(0, 0, 850, 850);
    this.stage.addChild(background);
    this.stage.mouseMoveOutside = true;
    this.adjustScale(this.buildings);

    this.drawArray(this.container, this.panelData);
    this.container.x = 0;
    this.container.y = 0;
    this.stage.addChild(this.container);

    this.drawBuildings(this.buildings, this.scale);

    this.stage.update();

    var lastMove = undefined;

    var self = this;

    // Panning
    this.stage.on("pressmove", function (event) {
      let x = event.stageX;
      let y = event.stageY;
      if (lastMove != undefined) {
        let deltaX = x - lastMove.x;
        let deltaY = y - lastMove.y;

        self.container.x += deltaX;
        self.container.y += deltaY;

        self.stage.update();
      }
      lastMove = {x: x, y: y};
    });

    this.stage.on("pressup", function () {
      lastMove = undefined;
    });
  }

  adjustScale(buildings) {
    if (!buildings || buildings.length === 0) return; // leave scale as default
    // we cannot determine canvas size
    // we are in a test or in a very impossible state
    // so we better not touch anything
    if(!this.stage.canvas) return;

    let all_x = ([].concat(...buildings)).map( (building) => building.x * this.scale );
    let all_y = ([].concat(...buildings)).map( (building) => building.y * this.scale );
    let max_x = Math.max(...all_x);
    let max_y = Math.max(...all_y);

    let ratio_y = this.stage.canvas.height * 1.0  / max_y;
    let ratio_x = this.stage.canvas.width * 1.0  / max_x;

    const MARGIN = 0.05;
    this.scale = this.scale * Math.min(ratio_y, ratio_x) * (1 - MARGIN);

  }

  drawBuildings(buildings) {
    if (!buildings || buildings.length === 0) {
      console.log("No Buildings!");
      return;
    }

    if (!this.scale) {
      console.log("No Scale - don't know how big the buildings should be!");
      return;
    }

    let line = new createjs.Shape();
    let color = createjs.Graphics.getRGB(0x010101, 1);

    line.graphics.setStrokeStyle(3);

    for (let i = 0; i < buildings.length; i++) {
      let building = buildings[i];
      let firstPoint = building[0];
      let nextPoint = null;

      line.graphics.beginStroke(color);

      line.graphics.moveTo(firstPoint.x * this.scale, firstPoint.y * this.scale);

      for (let j = 1; j < building.length; j++ ) {
        nextPoint = building[j];
        line.graphics.lineTo(nextPoint.x * this.scale, nextPoint.y * this.scale);
        line.graphics.moveTo(nextPoint.x  * this.scale, nextPoint.y * this.scale);
      }
      line.graphics.lineTo(firstPoint.x  * this.scale, firstPoint.y * this.scale );
      line.graphics.endStroke();

    }

    this.container.addChild(line);
  }

  refreshPanels(panelData) {
    this.panelData = panelData;

    for (let i = 0; i < this.panels.length; i++) {
      this.container.removeChild(this.panels[i]);
    }

    this.drawArray(this.container, this.panelData);

    let selectedPanel = this.selectedPanel;
    this.selectedPanel = undefined;
    this.selectPanel(selectedPanel);
    this.setOverlay(this.overlay);

    this.subarrayDisplay.didModifyPanels(panelData);

    this.stage.update();
  }

  drawArray(container, panels) {
    let treatCoordinatesAsCenterpoints = this.buildings && this.buildings.length > 0;
    for (let i = 0; i < panels.length; i++) {
      let box = new Panel(panels[i], this.isDualTilt, this.scale, treatCoordinatesAsCenterpoints);
      container.addChild(box);
      this.panels.push(box);

      box.on("click", () => {
        this.selectPanel(i);
      });
    }
  }

  selectPanel(panelIndex) {
    let panel = this.panels[panelIndex];
    if (this.selectedPanel !== undefined) {
      let previousPanel = this.panels[this.selectedPanel];
      previousPanel.deselect();
    }
    if (this.selectedPanel === panelIndex) {
      this.selectedPanel = undefined;
    } else {
      this.selectedPanel = panelIndex;
      panel.select();
    }
    this.stage.update();
  }

  setZoom(zoomLevel) {
    this.container.scaleX = zoomLevel;
    this.container.scaleY = zoomLevel;

    this.stage.update();
  }

  setOverlay(overlay) {
    this.overlay = overlay;
    this.panels.forEach((panel) => {
      panel.setOverlay(overlay);
    });

    this.stage.update();
  }

  addSeismicAnchor() {
    if (this.selectedPanel !== undefined) {
      this.panelData[this.selectedPanel].data.seismic_anchors++;
      this.panels[this.selectedPanel].redrawOverlays();
      this.stage.update();
      this.subarrayDisplay.didModifyPanels(this.panelData);
    }
  }

  removeSeismicAnchor() {
    if (this.selectedPanel !== undefined) {
      let seismicAnchors = this.panelData[this.selectedPanel].data.seismic_anchors;
      if (seismicAnchors > 0) {
        this.panelData[this.selectedPanel].data.seismic_anchors--;
        this.panels[this.selectedPanel].redrawOverlays();
        this.stage.update();
        this.subarrayDisplay.didModifyPanels(this.panelData);
      }
    }
  }
}

export default ArrayVisualization;
