<template >
  <div class="matrix">
    {{ flexibilityMethod }}
    <div class="container">
      <Sequence
        class="vertical-protein"
        v-if="showProtein"
        :protein="protein"
        :from="Number.NEGATIVE_INFINITY"
        :to="Number.POSITIVE_INFINITY"
        :colorBy="() => 'darkgrey'"
      />
      <div :id="`ccmatrix-stage-${protein.name}-${flexibilityMethod}`"></div>
    </div>
    <Sequence
      v-if="showProtein"
      :protein="protein"
      :from="Number.NEGATIVE_INFINITY"
      :to="Number.POSITIVE_INFINITY"
      :colorBy="() => 'darkgrey'"
    />
  </div>
</template>

<script>
import { scaleLinear } from "d3";
import Konva from "konva";
import Sequence from "../../StraightenedAcids/Sequence";

export default {
  props: {
    correlationMatrix: Array,
    protein: Object,
    flexibilityMethod: String,
    showProtein: Boolean,
  },

  components: {
    Sequence,
  },

  data() {
    return {
      config: {
        width: 400,
        height: 400,
      },
    };
  },
  mounted() {
    this.$nextTick(() => {
      // first we need to create a stage
      let stage = new Konva.Stage({
        container: `ccmatrix-stage-${this.protein.name}-${this.flexibilityMethod}`, // id of container <div>
        width: this.config.width,
        height: this.config.height,
      });

      // then create layer
      let layer = new Konva.Layer({
        listening: false,
      });
      for (let row = 0; row < this.correlationMatrix.length; row++) {
        for (let column = 0; column <= row; column++) {
          if (column <= row) {
            const correlationCoefficient = this.correlationMatrix[row][column];
            let square = new Konva.Rect(
              this.squareConfig(correlationCoefficient, row, column)
            );
            layer.add(square);
            let opposite_square = new Konva.Rect(
              this.squareConfig(correlationCoefficient, column, row)
            );
            layer.add(opposite_square);
          }
        }
      }
      // add the layer to the stage
      stage.add(layer);

      // // draw the image
      // layer.draw();
      // stage.draw();
    });
  },

  methods: {
    squareConfig(value, line_index, square_index) {
      return {
        x: square_index * this.squareSize,
        y: line_index * this.squareSize,
        width: this.squareSize + 1,
        height: this.squareSize + 1,
        fill: this.colorScale(parseFloat(value)),

        perfectDrawEnabled: false,
        strokeEnabled: false,
      };
    },
  },

  computed: {
    squareSize() {
      return this.config.width / this.correlationMatrix.length;
    },

    colorScale() {
      return scaleLinear()
        .domain([-1, 0, 1])
        .range(["#1f77b4", "white", "#ff7f0e"]);
    },
  },
};
</script>

<style scoped>
.vertical-protein {
  width: 400px;
  margin-right: -400px;
  transform: rotate(90deg);
  transform-origin: top left;
}
.container {
  display: flex;
}
</style>