export const backend = {
	endpont: __IS_BUILD__
		? window.location.origin + __SUBPATH__ + "api.php"
		: "http://localhost/bugreport/api.php",

	/* ----------------------------------------------------
	 * Vsebecne API volanie
	 */
	call(method, data, callback) {
		var xhttp = new XMLHttpRequest();
		xhttp.withCredentials = true;
		xhttp.onreadystatechange = function() {
			if (this.readyState == 4) {
				if (this.status == 200) {
					if (callback != null) callback(JSON.parse(this.responseText));
				} else {
					if (callback != null) callback({'status': 'ERROR', 'message': 'HTTP STATUS ' + this.status});
				}
			}
		}
		var form_data  = new FormData();
		Object.keys(data).forEach(key => {
			let val = data[key];
			if (typeof val == 'object') val = JSON.stringify(val);
			form_data.append(key, val);
		});
		xhttp.open('POST', this.endpont + '?action=' + method);
		//xhttp.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
		xhttp.send(form_data);
	},

	callPromise(method, data) {
		return new Promise((resolve, reject) => {
			this.call(method, data, function(response) {
				if (response.status == 'OK') {
					resolve(response.data);
				} else {
					reject(response.msg);
				}
			});
		})
	},

	/* ----------------------------------------------------
	 * API akcie
	 */
	help() {
		return this.callPromise('help', {});
	},

	add(title, description, status, group, priority) {
		return this.callPromise('add', {
			title: title,
			description: description,
			status: status,
			group: group,
			priority: priority});
	},

	update(id, report_data) {
		return this.callPromise('update', {report_id: id, report_data: report_data});
	},

	delete(id) {
		return this.callPromise('delete', {report_id: id});
	},

	get(id) {
		return this.callPromise('get', {report_id: id});
	},

	getAll() {
		return this.callPromise('getAll', {});
	},

	getAllGrouped(status) {
		return this.callPromise('getAllGrouped', {});
	},

	updateOrdnum(ordnums) {
		return this.callPromise('updateOrdNum', {ordnums: ordnums});
	},

	updateStatus(id, status) {
		return this.callPromise('updateStatus', {report_id: id, status: status});
	},

	attachmentAdd(report_id, attachment_type, attachment_content) {
		return this.callPromise('attachmentAdd', {report_id: report_id, attachment_type: attachment_type, attachment_content: attachment_content});
	},

	attachmentUpdate(attachment_id, attachment_content) {
		return this.callPromise('attachmentUpdate', {attachment_id: attachment_id, attachment_content: attachment_content});
	},

	attachmentGetAll(report_id) {
		return this.callPromise('attachmentGetAll', {report_id: report_id});
	},

	attachmentDelete(attachment_id) {
		return this.callPromise('attachmentDelete', {attachment_id: attachment_id});
	},

};
