// @require DOMParser - browser
// @require jQuery, moment, p5UI__notifyAjaxCallback
if ('undefined' === typeof BASE_URL) throw "Missing BASE_URL"
if ('undefined' === typeof USER) throw "Missing USER"
if ('undefined' === typeof CALENDAR_NODE_ID) throw "Missing CALENDAR_NODE_ID"

jQuery(document).ready(function() {
	var cached = {};
	jQuery('#' + CALENDAR_NODE_ID).fullCalendar({
		header: {
			left: 'prev,next today',
			center: 'title',
			right: ''
		},
		editable: false,
		lang: "pl",
		titleFormat: "MMMM YYYY [("+USER+")]",
		editable: false,
		viewRender: function (view, element) {
			getWorkingHours(moment(view.intervalStart).format("YYYY-MM"));
		},
		eventLimit: true, // allow "more" link when too many events
		/*events: [
			{
				title: '10:00 - 16:00',
				start: '2016-08-01',
				className: 'workingHours'
			}
		],*/
	});

	function parseWfsFeatureMember(featureMember) { // HTMLCollection.children @returns event { id, start_work_hour, end_work_hour, date }
		// gml:featureMember / p5_default_db:GRAFIK_PRACY / p5_default_db:ID
		// gml:featureMember / p5_default_db:GRAFIK_PRACY / p5_default_db:START_WORK_HOUR
		// gml:featureMember / p5_default_db:GRAFIK_PRACY / p5_default_db:END_WORK_HOUR
		// gml:featureMember / p5_default_db:GRAFIK_PRACY / p5_default_db:DATE
		if (!featureMember) return null
		if (!featureMember.children.length) return null
		var grafik = featureMember.children[0]
		if (!grafik) return null
		if (!grafik.children.length) return null
		var calendarItem = {
			id: null,
			start_work_hour: null,
			end_work_hour: null,
			date: null,
		}
		var i = 0
		for (i = 0; i < grafik.children.length; i++) {
			var field = grafik.children[i]
			switch (field.localName) {
				case 'ID': calendarItem.id = field.textContent; break;
				case 'START_WORK_HOUR': calendarItem.start_work_hour = field.textContent; break;
				case 'END_WORK_HOUR': calendarItem.end_work_hour = field.textContent; break;
				case 'DATE': calendarItem.date = field.textContent; break;
			}
		}
		if (!calendarItem.id) return null
		if (!calendarItem.start_work_hour) return null
		if (!calendarItem.end_work_hour) return null
		if (!calendarItem.date) return null
		return calendarItem
	}

	function getWorkingHours(date) {
		if (cached[date] != true) {
			cached[date] = true;
			var link = BASE_URL + 'wfs-data.php/default_db/?SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&TYPENAME=p5_default_db:GRAFIK_PRACY&SRSNAME=EPSG:3003&Filter=<ogc:Filter><ogc:And><ogc:PropertyIsLike wildCard="*" singleChar="^" escapeChar="!"><ogc:PropertyName>DATE</ogc:PropertyName><ogc:Literal>'+date+'-*</ogc:Literal></ogc:PropertyIsLike><ogc:PropertyIsEqualTo><ogc:PropertyName>L_APPOITMENT_USER</ogc:PropertyName><ogc:Literal>' + USER + '</ogc:Literal></ogc:PropertyIsEqualTo></ogc:And></ogc:Filter>';
			//console.log(link);
			if (DBG) console.log('DBG API fetch', link);

			window.fetch(link, {
				method: 'GET',
				credentials: 'same-origin',
			}).then(function (response) {
				return response.text()
			}).then(function (txtResponse) {
				// return jQuery.parseXML(txtResponse)
				var xmlParser = new DOMParser();
				return xmlParser.parseFromString(txtResponse, "text/xml");
			}).then(function (xmlResponse) {
				if (!xmlResponse.children.length) throw "Missing response xml root element"
				return xmlResponse.children[0]
			}).then(function (wfsFeatureCollection) {
				if ('wfs:FeatureCollection' !== wfsFeatureCollection.tagName) throw "Missing wfs:FeatureCollection element"
				var events = []
				for (var i = 0; i < wfsFeatureCollection.children.length; i++) {
					events.push(parseWfsFeatureMember(wfsFeatureCollection.children[i]))
				}
				return events.filter(function (item) { return !!item; })
			}).then(function __eventsRender(events) {
				if (DBG) console.table(events);
				var calJqNode = jQuery('#' + CALENDAR_NODE_ID)
				events.forEach(function(item) {
					var source = {};
					if (moment(item.start_work_hour, "HH:mm:ss").format("HH:mm") != "00:00") {
						source["title"] = moment(item.start_work_hour, "HH:mm:ss").format("HH:mm")+" - "+moment(item.end_work_hour, "HH:mm:ss").format("HH:mm");
						source["className"] = 'workingHours';
					} else {
						source["title"] = "Uzupełnij";
						source["className"] = 'empty';
					}
					source["start"] = item.date;
					source["url"] = BASE_URL + 'index.php?_route=ViewTableAjax&namespace=default_db/GRAFIK_PRACY#EDIT/'+item.id;
					calJqNode.fullCalendar('renderEvent', source, true);
				})
			}).catch(function (e) {
				p5UI__notifyAjaxCallback({ type: 'error', msg: e })
				console.warn(e)
			})
		}
    }

});
