import { trimStart } from '../common/qmsCKEditorUtil';

export const HTML_ATTRIBUTES = {
	COORDS: 'coords',
	HREF: 'href',
	SHAPE: 'shape',
	NAME: 'name',
	TARGET: 'target',
	USE_MAP: 'usemap',
	ALT: 'alt',
	WIDTH: 'width',
	HEIGHT: 'height',
	SRC: 'src',
	ID: 'id',
	SAVED_SRC: 'savedsrc'
}


export const HTML_ELEMENTS = {
	MAP: 'map',
	IMAGE: 'img',
	AREA: 'area'
}


export const IMAGEMAP_ATTRIBUTES = {
	MAP_AREAS: 'mapareas',
	MAP_NAME: 'mapname' ,
	MAP_WIDTH: 'mapwidth',
	MAP_HEIGHT: 'mapheight',
	IMAGE_USE_MAP: 'imageusemap',
	IMAGE_SAVED_SRC: 'imagesavedsrc',
	IMAGE_SRC: 'src',//It is already defined by the image plugin
	IMAGE_WIDTH: 'imagewidth',
	IMAGE_HEIGHT: 'imageheight',
}

export const IMAGEMAP_COMMANDS = {
	IMAGEMAP_DIALOG: 'imagemapdialog',
	IMAGEMAP: 'imagemap',
	RESIZE_IMAGEMAP: 'resizeimagemap'
}

export const IMAGEMAP_ELEMENTS = {
	MAP: 'qmsmap',
	IMAGE: 'image'//It is already defined by the image plugin
}

export function createInsertedEvent(mapname){
	return trimStart(mapname, '#') + '_inserted';
}

export function createRemovedEvent(mapname){
	return trimStart(mapname, '#') + '_removed';
}

export function createResizedEvent(mapname){
	return trimStart(mapname, '#') + '_resized';
}

export function parsePixelToFloat(pixel, fractionDigits){
	if(pixel){
		pixel = pixel.toString().replaceAll('px', '');
		try
		{
			return Number.parseFloat(pixel).toFixed(fractionDigits);
		}
		catch{

		}
	}
	return 0;
}

function isMapNode(lowerCaseNameObject, node){
	return node.is('element', IMAGEMAP_ELEMENTS.MAP)
			&& node.hasAttribute(IMAGEMAP_ATTRIBUTES.MAP_NAME)
			&& lowerCaseNameObject[getLowerCaseMapName(node)];
}

function getLowerCaseMapName(node){
	return node.getAttribute(IMAGEMAP_ATTRIBUTES.MAP_NAME).toLowerCase();
}

export function findMapNodes(names, range) {
	if(!names) { return []; }

	const lowerCaseNameObject = {};
	names.forEach(name => {
		let lowerCase = name.toLowerCase();
		lowerCaseNameObject[lowerCase] = lowerCase;
	});

    const nodes = {};
    for ( const value of range.getWalker() ) {
        const node = value.item;
        if (isMapNode(lowerCaseNameObject, node)) {
			let mapname = getLowerCaseMapName(node);
            nodes[mapname] = node;
        }
    }
    return Object.keys(nodes).map(key => nodes[key]);
};


export function findFirstMapNode(name, range) {
	if(!name) { return null; }

	const lowerCaseNameObject = {};
	let lowerCase = name.toLowerCase();
	lowerCaseNameObject[lowerCase] = lowerCase;

    for ( const value of range.getWalker() ) {
        const node = value.item;
        if (isMapNode(lowerCaseNameObject, node)) {
			return node;
        }
    }
    return null;
};

export function resizeAreaWidth(area, ratio) {
	var coords = area.coords.split(',');
	switch (area.shape) {
		case 'circle':
			coords[0] = Math.round(coords[0] * ratio); // Moves center point's left coordinate
			coords[2] = Math.round(coords[2] * ratio); // Ajust radius
			area.coords = coords.join(',');
			return area;
			case 'rect':
			case 'poly':
			// Moves each point's left coordinate
			for (var i = 0; i < coords.length; i += 2) {
				if (i >= coords.length) { break; }
				coords[i] = Math.round(coords[i] * ratio);
			}
			area.coords = coords.join(',');
			return area;
	}
};

export function resizeAreaHeight(area, ratio, widthChanged) {
	var coords = area.coords.split(',');
	switch (area.shape) {
		case 'circle':
			coords[1] = Math.round(coords[1] * ratio); // Moves center point's top coordinate
			if (!widthChanged) {
				coords[2] = Math.round(coords[2] * ratio); // Ajust radius
			}
			area.coords = coords.join(',');
			return area;
		case 'rect':
		case 'poly':
			// Moves each point's top coordinate
			for (var i = 1; i < coords.length; i += 2) {
				if (i >= coords.length) { break; }
				coords[i] = Math.round(coords[i] * ratio);
			}
			area.coords = coords.join(',');
			return area;
	}
};

export function drawMap(imageSrc, imageWidth, imageHeight, areas, callback){
	if(areas && areas.length > 0){
		try
		{
			var tempImage = new Image(imageWidth, imageHeight);
			tempImage.src = imageSrc;
			tempImage.addEventListener("load", () =>{
				var canvas = document.createElement('canvas');
				var context = canvas.getContext('2d');

				canvas.width = imageWidth;
				canvas.height = imageHeight;
				context.drawImage(tempImage, 0, 0, imageWidth, imageHeight);
				context.strokeStyle = "#FF0000";
				context.lineWidth = 1;

				for (var i = 0; i < areas.length; i++) {
					const area = areas[i];
					const coords = area.coords.split(',');
					switch (area.shape) {
						case 'circle':
							context.beginPath();
							context.arc(coords[0], coords[1], coords[2], 0, Math.PI * 2, true);
							context.closePath();
							context.stroke();
							break;

						case 'poly':
							context.beginPath();
							context.moveTo(coords[0], coords[1]);
							for (var j = 2; j < coords.length; j += 2) {
								context.lineTo(coords[j], coords[j + 1]);
							}
							context.closePath();
							context.stroke();
							break;

						default:
							context.strokeRect(coords[0], coords[1], coords[2] - coords[0], coords[3] - coords[1]);
							break;
					}
				}
				let newSrc = imageSrc;
				let oldSrc = imageSrc;
				try
				{
					newSrc = canvas.toDataURL();
				}
				catch(err){

				}
				if(callback){
					callback(oldSrc, newSrc);
				}

			}, false);
		}
		catch(err){
			 console.log(err);
		}
	}
}
