import { editorTag, Image, ImageStore } from '../models/editor-model';

/** Update the images map object that contains all of the images
 *  There is additional logic in here to allow you to update
 *  a key value by passing in an oldKey value to update.
 *  Additionally it handles trying to set the form id
 *  value if the id value that has been passed in is unknown.
 */
export function updateImagesMap(
	images: ImageStore,
	key: string,
	newValue: Image,
	oldKey: string = null
): void {
	if (oldKey) {
		images.delete(oldKey);
	}
	if (!newValue.id) {
		newValue = incrementHighestId(newValue, images);
		images.set(key, newValue);
	} else {
		images.set(key, newValue);
	}

	const editor = document.getElementsByTagName(editorTag);
	if (!editor && editor.length <= 0) {
		return;
	}
	// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
	(editor[0] as any).images = images;
	editor[0].setAttribute('images', JSON.stringify(images));
}
function incrementHighestId(newValue: Image, images: ImageStore) {
	const ids: number[] = [];
	images.forEach(value => {
		ids.push(parseInt(value.id.replace(/^\D+/, '')));
	});
	if (ids.length === 0) {
		newValue.id = `0`;
	} else if (ids.length > 1) {
		let max = Math.max(...ids);
		max++;
		newValue.id = max.toString();
	} else {
		let incrementedId = ids[0];
		incrementedId++;
		newValue.id = incrementedId.toString();
	}
	newValue.id = `img-src-${newValue.id}`;
	return newValue;
}
