export default class Admin {

	constructor(oSpot) {
		this.spot = oSpot;
	}

	pageInit(asHash) {
		this.spot.get('admin_get', (asElemTypes) => {this.setProjects(asElemTypes);});
		$('#new').addButton('new', this.spot.lang('new_project'), 'new', () => {this.createProject();});
		$('#toolbox').addButton('refresh', this.spot.lang('update_project'), 'refresh', () => {this.updateProject();});
	}

	onFeedback(sType, sMsg, asContext) {
		delete asContext.a;
		delete asContext.t;
		sMsg += ' (';
		$.each(asContext, function(sKey, sElem) {
			sMsg += sKey+'='+sElem+' / ' ;
		});
		sMsg = sMsg.slice(0, -3)+')';
		$('#feedback').append($('<p>', {'class': sType}).text(sMsg));
	}

	setProjects(asElemTypes) {
		let aoEvents = [
			{
				on:'change', 
				callback: (oEvent) => {this.commit(oEvent);}
			},
			{
				on:'keyup',
				callback: (oEvent) => {this.waitAndCommit(oEvent);}
			}
		];
		let aoChangeEvent = [aoEvents[0]];

		$.each(asElemTypes, (sElemType, aoElems) => {
			$.each(aoElems, (iKey, oElem) => {
				var sElemId = sElemType+'_'+oElem.id;
				var bNew = ($('#'+sElemId).length == 0);

				var $Elem = (bNew?$('<tr>', {'id': sElemId}):$('#'+sElemId))
					.data('type', sElemType)
					.data('id', oElem.id);

				if(oElem.del) $Elem.remove();
				else if(!bNew) {
					$Elem.find('input').each((iKey, oInput) => {
						var $Input = $(oInput);
						if($Input.attr('name') in oElem && $Input.attr('type')!='date') $Input.val(oElem[$Input.attr('name')]);
					});
				}
				else {
					$Elem.append($('<td>').text(oElem.id || ''));
					switch(sElemType) {
						case 'project':
							$Elem
								.append($('<td>').addInput('text', 'name', oElem.name, aoEvents))
								.append($('<td>', {'class': 'mode'}).text(oElem.mode))
								.append($('<td>').addInput('text', 'codename', oElem.codename, aoEvents))
								.append($('<td>').addInput('date', 'active_from', oElem.active_from, aoChangeEvent))
								.append($('<td>').addInput('date', 'active_to', oElem.active_to, aoChangeEvent))
								.append($('<td>').addButton('close fa-lg', '', 'del_proj', (oEvent)=>{this.del(oEvent);}));
							break;
						case 'feed':
							$Elem
								.append($('<td>').addInput('text', 'ref_feed_id', oElem.ref_feed_id, aoEvents))
								.append($('<td>').addInput('number', 'id_spot', oElem.id_spot, aoEvents))
								.append($('<td>').addInput('number', 'id_project', oElem.id_project, aoEvents))
								.append($('<td>').text(oElem.name))
								.append($('<td>').text(oElem.status))
								.append($('<td>').text(oElem.last_update))
								.append($('<td>').addButton('close fa-lg', '', 'del_feed', (oEvent)=>{this.del(oEvent);}));
							break;
						case 'spot':
							$Elem
								.append($('<td>').text(oElem.ref_spot_id))
								.append($('<td>').text(oElem.name))
								.append($('<td>').text(oElem.model))
							break;
						case 'user':
							$Elem
								.append($('<td>').text(oElem.name))
								.append($('<td>').text(oElem.language))
								.append($('<td>').text(oElem.timezone))
								.append($('<td>').addInput('number', 'clearance', oElem.clearance, aoEvents))
							break;
					}

					$Elem.appendTo($('#'+sElemType+'_section').find('table tbody'));
				}
			});
		});
	}

	createProject() {
		this.spot.get('admin_new', this.setProjects);
	}

	updateProject() {
		this.spot.get(
			'update_project',
			(asData, sMsg) => {this.spot.onFeedback('success', sMsg, {'update':'project'});},
			{},
			(sMsg) => {this.spot.onFeedback('error', sMsg, {'update':'project'});}
		);
	}

	commit(oEvent) {
		let $Elem = $(oEvent.currentTarget);
		if(typeof this.spot.tmp('wait') != 'undefined') clearTimeout(this.spot.tmp('wait'));

		var sOldVal = $Elem.data('old_value');
		var sNewVal = $Elem.val();
		if(sOldVal != sNewVal) {
			$Elem.data('old_value', sNewVal);

			var $Record = $Elem.closest('tr');
			var asInputs = {
				type:	$Record.data('type'),
				id: 	$Record.data('id'),
				field:	$Elem.attr('name'),
				value:	sNewVal
			};

			this.spot.get(
				'admin_set',
				(asData) => {
					this.spot.onFeedback('success', this.spot.lang('admin_save_success'), asInputs);
					this.setProjects(asData);
				},
				asInputs,
				(sError) => {
					$Elem.data('old_value', sOldVal);
					this.spot.onFeedback('error', sError, asInputs);
				}
			);
		}
	}

	waitAndCommit(oEvent) {
		if(typeof this.spot.tmp('wait') != 'undefined') clearTimeout(this.spot.tmp('wait'));
		this.spot.tmp('wait', setTimeout(() => {this.commit(oEvent);}, 2000));
	}

	del(oEvent) {
		var $Record = $(oEvent.currentTarget).closest('tr');
		var asInputs = {
			type: $Record.data('type'),
			id: $Record.data('id')
		};

		this.spot.get(
			'admin_del',
			(asData) => {
				this.spot.onFeedback('success', this.spot.lang('admin_save_success'), asInputs);
				this.setProjects(asData);
			},
			asInputs,
			(sError) => {
				this.spot.onFeedback('error', sError, asInputs);
			}
		);
	}
}