<script>
    import { onMount } from "svelte";
    import { data_store } from '../../store'

    import {
        width,
        height,
        cellWidth,
        cellHeight,
        channel_number,
        chart_row_num,
        dataset_min,
        dataset_max,
        colormap,
        last_row_num,
        interval,
        frameID
    } from '../canvas_properties';
    import * as d3 from 'd3';

    let colorScale = d3.scaleLinear()
                        .domain([0, 1000]) //([$dataset_min, $dataset_max])
                        .range([0,1]);
    let canvas;
    let ctx;
    let chart_border;
    
    $: $cellWidth = $width/$channel_number, console.log("CellWidth: ", $cellWidth)

    onMount(() => {
        ctx = canvas.getContext('2d');
        chart_border = document.getElementById("chart_border");
        $width = chart_border.offsetWidth;
        $height = window.innerHeight-window.innerHeight/4;
        $channel_number = ($data_store.length != 0) ? $data_store[0].length : 1;
        $cellHeight = 10;
        $chart_row_num = ($height/$cellHeight)+1;
	});
    $: {
        console.log ({
            w: $width,
            h: $height,
            cW: $cellWidth,
            cH: $cellHeight
        }),
        draw()
    }
    window.addEventListener('resize', () => {
      draw()
    })
    // has to bve difined, could be random value or a Symbol() but this is sufficient

    $: {
        $last_row_num
        console.log("Lastrownumber", $last_row_num)
        draw()
    }
    $: $colormap, draw()

    let lastTime = window.performance.now()
    let current_time;
    let deltaTime;

    export function animate(newTime) {
        $frameID = requestAnimationFrame(animate);
        current_time = newTime;
        deltaTime = current_time - lastTime;

        if (deltaTime > $interval) {
            lastTime = current_time - (deltaTime % $interval)
            draw()
        }
    }
    function draw() {
        let dataRow;
        let posX;
        let posY;
        let row_number = ($data_store.length < $chart_row_num) ? $data_store.length : $chart_row_num;

        for (let y = 0; y < row_number; y++){
            dataRow = $data_store[y];
            posY = y * $cellHeight;
            for (let x = 0; x < dataRow.length; x++){
                posX = x * $cellWidth;
                ctx.fillStyle = getFill(dataRow[x]);
                ctx.fillRect(
                    posX,
                    posY, 
                    posX + $cellWidth,
                    $cellHeight
                );
            }
        }
    }

    export function download_image() {
        const image = new Image();
        image.src = canvas.toDataURL("image/png");

        // Create a download link and click it
        const link = document.createElement("a");
        link.download = "canvas_image.png";
        link.href = image.src;
        link.click();
    }

    export function clear_canvas() {
        ctx = canvas.getContext('2d');
        ctx.clearRect(0, 0, $width, $height);
    }

    function getFill(value) {
        return $colormap(colorScale(value))  // return d3.interpolateInferno(colorScale(value));
    }
</script>

<div class="col" id="chart">
    <div class="border rounded" id="chart_border">

        <canvas bind:this={canvas} width={$width} height={$height} />
    </div>
</div>
<style>
    canvas {
        width: 99%;
        height: 99%;
        margin-left: auto;
        margin-right: auto;
    }
</style>