/**
 * Use this class to ensure Google charts API javascript is loaded before running any google chart specific code.
 */
let isLoading = false;
export class GoogleChartsApi {

	/**
	 * Constructor
	 */
	constructor() {
		this.api = 'https://www.gstatic.com/charts/loader.js';
		this.scriptElement = this.getScriptElement();
	}

	/**
	 * Load the Google Maps API javascript
	 */
	load() {
		return new Promise((resolve) => {
			if (isLoading === false) {
				isLoading = true;
				this.scriptElement = document.createElement('script');
				document.body.appendChild(this.scriptElement);
				this.scriptElement.addEventListener('load', () => {
					// load google charts
					this.loadPackages().then(() => {
						resolve();
					});
				});
				this.scriptElement.async = true;
				this.scriptElement.src = this.api;
			} else {
				this.scriptElement.addEventListener('load', () => {
					this.loadPackages().then(() => {
						resolve();
					});
				});
			}
		});
	}

	loadPackages() {
		return google.charts.load('current', { 'packages': ['corechart', 'bar'] });
	}

	getScriptElement() {
		return document.querySelector(`script[src='${this.api}']`);
	}
}
