<template>
  <canvas
    ref="map" style="max-width: 25%;"
    :width="props.width"
    :height="props.height"
  ></canvas>
</template>
<script setup lang="ts">
import { ref, onMounted, watch, computed } from 'vue';
import {MapContext, MapDrawable} from './helpers';

const map = ref<HTMLCanvasElement>();

const props = defineProps<{
  width: number,
  height: number,
  offsetX: number,
  offsetY: number,
  dpi: number,
  scale: number,
  layers: MapDrawable[]
}>()

const emit = defineEmits<{
  mousedown: [MouseEvent]
}>()

const mapContext = computed(() => {
  return {
    virtualHeight: props.height,
    virtualWidth: props.width,
    offsetX: props.offsetX,
    offsetY: props.offsetY,
    scale: props.scale,
    dpi: props.dpi,
  }
})

function redraw() {
  const ctx = {
    ctx: map.value!.getContext('2d')!,
    ...mapContext.value,
  };
  console.log('redraw', ctx.scale);
  ctx.ctx.fillStyle = 'black';
  ctx.ctx.fillRect(0, 0, ctx.virtualWidth, ctx.virtualHeight);
  for (const layer of props.layers) {
    layer.draw(ctx);
  }
}

watch(() => mapContext.value, redraw);

watch(() => props.layers, redraw);
onMounted(redraw);
</script>