<template>
  <canvas id="MCcanvas" width="480" height="320" />
</template>

<script setup>
import { onMounted, ref, watch } from "vue";
import { useRLStore } from "@/store/RLStore";

const rlstore = useRLStore();

const imageData = ref(null);

const renderImage = (width, height) => {
  const red = rlstore.getRed;
  const green = rlstore.getGreen;
  const blue = rlstore.getBlue;

  const rgbData = new Uint8ClampedArray(height * width * 4);
  for (let i = 0; i < height * width; i++) {
    const j = i * 4;
    rgbData[j] = red[i];
    rgbData[j + 1] = green[i];
    rgbData[j + 2] = blue[i];
    rgbData[j + 3] = 255;
  }

  imageData.value = rgbData;
};

const drawImage = (width, height) => {
  if (imageData.value) {
    const canvas = document.getElementById("MCcanvas");
    const context = canvas.getContext("2d");

    const image = new ImageData(imageData.value, width, height);
    context.putImageData(image, 0, 0);
  }
};

onMounted(() => {
  const height = rlstore.getHeight;
  const width = rlstore.getWidth;
  renderImage(width, height);
  drawImage(width, height);
});

watch(
  () => rlstore.trigger,
  () => {
    const height = rlstore.getHeight;
    const width = rlstore.getWidth;
    renderImage(width, height);
    drawImage(width, height);
  }
);
</script>

<style scoped></style>
