use crate::descriptors::DCT;
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;
use std::io::Cursor;
use console_error_panic_hook;

#[wasm_bindgen]
extern {
    fn alert(s: &str);
}

#[wasm_bindgen]
pub fn greet() {
    alert("Hello world!");
}

#[wasm_bindgen]
pub fn dctify(bytes: Vec<u8>) -> Vec<f64> {
	console_error_panic_hook::set_once();
	let reader = 
		image::io::Reader
		::new(Cursor::new(bytes)).with_guessed_format().unwrap();
	let img: image::DynamicImage = 
		reader
		.decode()
		.unwrap();
	let dct = DCT::new();
	let values = dct.dct(&img);
	Vec::from(values)
}

#[wasm_bindgen]
pub fn resize(bytes: Vec<u8>) -> Vec<u8> {
	console_error_panic_hook::set_once();
	let reader = 
		image::io::Reader
		::new(Cursor::new(bytes)).with_guessed_format().unwrap();

	let img: image::DynamicImage = 
		reader
		.decode()
		.unwrap();

	let resized = img.grayscale().thumbnail_exact(8, 8);
	let mut buffer: Vec<u8> = Vec::new();
	let mut writer = std::io::Cursor::new(&mut buffer);

	resized.write_to(&mut writer, image::ImageFormat::Png).unwrap();

	buffer
}