/* example calls

	let stapi = new StrapiCaller(); //defaults to events calls
	strapi.setParam("upcoming", "1");
	strapi.call((rsp) =>{
		//do something with json
	});


	all calls support:

		limit: [integer] limit num of results
		start: [integer] what result to start at, zero-based
		<<OR is it?>> 
		pagination[start]=0

	events params: 

		upcoming: if "1" then get's events on or after today's date
		past: if "1" then get's events before today's date, in reverse chrono order
		category: [string] exact name of a category to limit to


	online-resources params;

		limit to various tags:

		features: [string]
		mediums: [string]
		eras: [string]


*/


class StrapiCaller {
	constructor(api = "events"){
		this.url = location.protocol + "//" + location.hostname + "/api/";
		this.params = [];

		this.options =  {
			method: "GET", mode: 'cors', cache: 'no-cache',	credentials: 'same-origin',
			port: 1337,
			method: 'GET',
			headers: {
				'Content-Type': 'application/json',
				"Authorization": "bearer a726859da05533df07bed632ad3c8674604d24f364acdbac6d0565d90345f85a13698590e6a89d34860824fb7bcc5fab0befd946697e62d8ad2a85c27556511dbc743e8be186ab53df15383d0496f6a8c341b7ba7dd048ed32b87456b29aaa6df7a716a87c74c48d66ac51774b51b748d2f008547e413b78c4b65e2bfff12a0a"
			} //this is a public api key, so don't bother trying anything, punk
		}

		//prevent other apis via JS injection
		let allowedAPIs = ["events", "online-resources", "pages", "all-events", "podcasts"];
		if(!allowedAPIs.includes(api)) api = allowedAPIs[0];

		switch(api){
			case "online-resources":
				this.url += "getOnlineResources?";
				break;
				
			case "all-events":
				this.url += "getAllDisplay?";
				break;
			
			case "podcasts":
				this.url += "getPodcasts?[populate][0]=image&sort=date:desc&pagination[limit]=10&pagination[withCount]=true"
				break;

			default:
				this.url += 'getEvents?';
		}
	}



	setParam(name, value, allowEmpty = false){
		if(!allowEmpty) if(value == "" || value == null) return;
		//if found existing, just replace
		if(this.changeParam(name, value)) return;
		this.params.push(name + "=" + encodeURIComponent(value));
	}


	changeParam(name, value){
		for(let i=0;i<this.params.length;i++){
			let temp = this.params[i].split("=");
			if(temp[0] == name){
				this.params[i] = name + "=" + encodeURIComponent(value);
				return true;
			}
		}
	}

	removeParam(name){
		for(let i=0;i<this.params.length;i++){
			let temp = this.params[i].split("=");
			if(temp[0] == name){
				this.params.splice(i, 1);
				return;;
			}
		}
	}

	resetParams(){
		this.params = [];
	}


	static ResolveImage(obj){
		if(obj.data) obj = obj.data;
		if(obj.attributes) obj = obj.attributes;
		//if we find a new, strapi-based image
		if(obj.image && obj.image.data){
			return obj.image.data.attributes;
		}

		if(obj.image){
			return obj.image;
		}

		//look for image url leftover from Drupal
		if(obj.old_image && obj.old_image.length){
			return {
				url: obj.old_image.replace(/public\:\/\//, "/public/"), alternativeText: "" 
			}
		}

		return {
			url: "", alternativeText: ""
		}
	} 


	async call(callback){
		let url = this.url + this.params.join("&");

		try {
			let response = await fetch(url, this.options);		
			if (!response.ok) {
				let msg = `HTTP error! status: ${response.status}`;
				if(this.config.httpErrorHandler) this.config.httpErrorHandler(response);
				console.log(msg);
				return false;
			} else {
				let json = await response.json();
				// console.log(json)
				callback(json);
				
			}
		} catch(err){
			console.log(err);
			return {};
		}
	}

}
