const sax = require('sax');
const { isUrlRequest, urlToRequest } = require('loader-utils');
const ROOT_TAG_NAME = 'xxx-wxml-root-xxx';
const ROOT_TAG_START = `<${ROOT_TAG_NAME}>`;
const ROOT_TAG_END = `</${ROOT_TAG_NAME}>`;

const isSrc = (name) => name === 'src';

module.exports = function(content) {
	const xmlContent = `${ROOT_TAG_START}${content}${ROOT_TAG_END}`;
	const parser = sax.parser(false, { lowercase: true });
	const requests = [];
	const callback = this.async();

	const loadModule = (request) =>
		new Promise((resolve, reject) => {
			this.addDependency(request);
			this.loadModule(request, (err, src) => {
				if (err) {
					reject(err);
				}
				else {
					resolve(src);
				}
			});
	});

	parser.onattribute = ({ name, value }) => {
		if (
			!value ||
			!isSrc(name) ||
			!isUrlRequest(value) ) {
			return
		}

		const request = urlToRequest(value);
		requests.unshift(request);
	};

	parser.onend = async () => {
		try {
			for (const req of requests) {
				await loadModule(req);
			}
			callback(null, content);
		} catch (err) {
			callback(err, content);
		}

	};

	parser.write(xmlContent).close();

	return content
};
