class TemplateLoader {
	constructor() {
        this.cacheBusting = true;
        TemplateLoader.TemplateCache = {};    
    }
    
    async get(templateName) {
        if(!TemplateLoader.TemplateCache[templateName]) {
			try {
			TemplateLoader.TemplateCache[templateName] = await this.forceGet(templateName);
			} catch(e) {
				console.error(`Template ${templateName} not found`);
				return "";
			}
        }
        return TemplateLoader.TemplateCache[templateName];
    }

	async forceGet(templateName) {
		let url = `./templates/${templateName}.html`;
		if (this.cacheBusting) {
			url += "?v=" + new Date().getTime();
		}
		return await this.ajaxGet(url, { "Content-Type": 'text/html' });
    }
    
    ajaxGet(url, headers) {
		return new Promise((resolve, reject) => {
			var request = new XMLHttpRequest();
			request.open("GET", url, true);
			request.onreadystatechange = response => {
				if (request.readyState == 4) {
					if (request.status == 200) {
						resolve(request.responseText);
					} else {
						reject("finished with error", request.status);
					}
				}
			};
			request.onabort = response => {
				reject("abort");
			};
			request.onerror = response => {
				reject("error");
			};
			request.ontimeout = response => {
				reject("timeout");
			};
			for (let key in headers) {
				request.setRequestHeader(key, headers[key]);
			}
			request.send();
		});
	}
}
TemplateLoader.TemplateCache = {};