/**
 * Created by rockyl on 2019-11-16.
 */

const width = engine.findVariable('width', args, props);
const height = engine.findVariable('height', args, props);
const cutType = engine.findVariable('cutType', args, props);
const type = engine.findVariable('type', args, props);
const quality = engine.findVariable('quality', args, props);
let img = args;
if (typeof args === 'string') {
	img = new Image();
	img.onload = function () {
		deal();
	};
	img.onerror = function (e) {
		console.log(e);
	};
	img.src = args;
}
else {
	deal();
}

function deal() {
	let m = cutType === 'inner' ? Math.min : Math.max;
	let r = m(width / img.width, height / img.height);
	let imgWidth = img.width * r;
	let imgHeight = img.height * r;
	let x = (width - imgWidth) / 2;
	let y = (height - imgHeight) / 2;
	let canvas = document.createElement('canvas');
	canvas.width = width;
	canvas.height = height;
	let ctx = canvas.getContext('2d');
	ctx.translate(x, y);
	ctx.scale(r, r);
	ctx.drawImage(img, 0, 0);
	let dataUrl = canvas.toDataURL('image/' + type, quality);
	next('success', dataUrl);
}
