export default class Api {

	constructor({server, processPage, timezone, csrfToken, errorCode, lang}) {
		this.server = server;
		this.processPage = processPage;
		this.timezone = timezone;
		this.csrfToken = csrfToken;
		this.errorCode = errorCode;
		this.lang = lang;
	}

	async get(sAction, asParams = {}) {
		const response = await this.request(sAction, asParams, 'GET');
		return response.data;
	}

	async post(sAction, asParams = {}) {
		const response = await this.request(sAction, asParams, 'POST');
		return response.data;
	}

	async request(sAction, asParams = {}, method = 'GET') {
		const oUrl = new URL(this.processPage, this.server);

		const sUrlParams = new URLSearchParams({
			...asParams,
			a: sAction,
			t: this.timezone
		}).toString();

		const asOptions = {
			method,
			headers: {'Accept': 'application/json'}
		};

		if(method === 'GET') {
			oUrl.search = sUrlParams;
		}
		else {
			asOptions.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
			asOptions.headers['X-CSRF-Token'] = this.csrfToken;
			asOptions.body = sUrlParams;
		}

		const oRequest = await fetch(oUrl, asOptions);

		if(!oRequest.ok) {
			throw new Error('Error HTTP ' + oRequest.status + ': ' + oRequest.statusText);
		}

		const oResponse = await oRequest.json();
		oResponse.desc = this.lang.parse(oResponse.desc);

		if(oResponse.result == this.errorCode) {
			throw oResponse.desc;
		}

		return oResponse;
	}
}
