<script setup lang="ts">
import { HtmlHTMLAttributes, onMounted, ref } from 'vue';
import { grayScale } from "../processing/gray-scale.ts";

const canvas = ref<HTMLCanvasElement | null>(null);
let img: HTMLImageElement;
let ctx: CanvasRenderingContext2D;
onMounted(() => {
  ctx = canvas.value!.getContext('2d')!;
})

function onFileChange(event: Event) {
  const files = (event.target as HTMLInputElement).files!;
  const reader = new FileReader();
  reader.onload = function(event) {
    img = new Image();
    img.onload = () => {
      ctx.drawImage(img, 0, 0);
      const imageData = ctx.getImageData(0, 0, img.width, img.height);
      ctx.putImageData(imageData, 0, 0);
    }
    img.src = event.target!.result as string;
  }
  reader.readAsDataURL(files[0]);
}

function grayScaleApply() {
    const ctx = canvas.value!.getContext('2d')!;
    const imageData = ctx.getImageData(0, 0, canvas.value!.width, canvas.value!.height);
    const pixels = imageData.data;
    grayScale(pixels);
    ctx.putImageData(imageData, 0, 0);

}

function blackAndWhite(){
  ctx.drawImage(img, 0, 0, canvas.value!.width, canvas.value!.height);

  let imgPixels = ctx.getImageData(0, 0, canvas.value!.width, canvas.value!.height);
  for(let y = 0; y < imgPixels.height; y++){
      for(let x = 0; x < imgPixels.width; x++){
          let i = (y * 4) * imgPixels.width + x * 4;
          let avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
          if (avg < 150){
            imgPixels.data[i] = 0;
            imgPixels.data[i + 1] = 0;
            imgPixels.data[i + 2] = 0;
          }
          else{
            imgPixels.data[i] = 255;
            imgPixels.data[i + 1] = 255;
            imgPixels.data[i + 2] = 255;
          }
      }
  }
  ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
}

function onChangeSlideWidth(event: Event) {
  const slider = event.target as HTMLInputElement;
  const width = parseInt(slider.value)/100 * img.width;

  canvas.value!.width = width;
  ctx.drawImage(img, 0, 0, width, canvas.value!.height);
} 

function onChangeSlideHeight(event: Event) {
  const slider = event.target as HTMLInputElement;
  const height = parseInt(slider.value)/100 * img.width;

  canvas.value!.height = height;
  ctx.drawImage(img, 0, 0, canvas.value!.width, height);
} 

</script>

<template>
  <input type="file" @change="onFileChange">
  <button @click="grayScaleApply">grayScale</button>
  <button @click="blackAndWhite">blackAndWhite</button>
  <canvas ref="canvas" width="500" height="500"></canvas>
  <input type="range" min="1" max="200" value="100" class="slider" id="myRange" @change="onChangeSlideWidth">
  <input type="range" min="1" max="200" value="100" class="slider" id="myRange" @change="onChangeSlideHeight" orient="vertical">
</template>
