let handsonTable;

// This example creates a date editor that will show MM/YYYY
const TA_EDITOR_HORA = Handsontable.editors.TextEditor.prototype.extend();

TA_EDITOR_HORA.prototype.createElements = function () {
	Handsontable.editors.TextEditor.prototype.createElements.apply(this, arguments);

	// You need to require/import the "inputmask" library
	var im = new Inputmask('99:99');

	// Create password input and update relevant properties
	this.TEXTAREA = document.createElement('input');
	this.TEXTAREA.setAttribute('type', 'text');
	this.TEXTAREA.className = 'text';
	im.mask(this.TEXTAREA);
	this.textareaStyle = this.TEXTAREA.style;
	this.textareaStyle.width = 0;
	this.textareaStyle.height = 0;

	// Replace textarea with password input
	Handsontable.dom.empty(this.TEXTAREA_PARENT);
	this.TEXTAREA_PARENT.appendChild(this.TEXTAREA);

};


function defaultConfigHandsonTable() {
	let container = document.getElementById("divHandsonTable");

	handsonTable = new Handsontable(container, {
		data: [],
		stretchH: 'all',
		rowHeaders: true,
		colHeaders: ['DNI', 'Apellidos y Nombres', 'Sede', 'Marcacion de entrada'],
		columns: [
			{
				data: "trabajador_dni"
			},
			{
				data: "trabajador_nombres"
			},
			{
				data: "sede_id",
				className: "text-center"
			},
			{
				data: "marcacion_entrada",
				className: 'text-center',
				editor: TA_EDITOR_HORA,
				type: 'time',
				timeFormat: 'HH:mm',
				correctFormat: true,
				allowInvalid: false
			}
		]
	});
}

const addRowHandsonTable = () => {
	handsonTable.alter('insert_row', handsonTable.countRows());
};


function agregarEventoTecladoHandsonTable() {
	Handsontable.Dom.addEvent(document.body, 'keydown', function (e) {
		if (e.keyCode === 13 && handsonTable) {
			addRowHandsonTable()
		}
	});
}

const listarSedes = (selectorName) => {
	ajaxWebService.get(URI_SEDES).then((result) => {
		let sedes = result.data;
		sedes = _.orderBy(sedes, s => s.descripcion);
		let html = `<option value="">[SELECCIONE]</option>`;
		sedes.forEach(sede => html += `<option value="${sede.codigo}">${sede.descripcion}</option>`);
		$(`${selectorName}`).html(html);
		$(selectorName).select2();
	});
};

function registrarAsistencias() {
	swal(
		{
			type: 'success',
			title: '¡Asistencias registradas!',
			showConfirmButton: false,
			timer: 1500
		}
	);
}


$(() => {
	defaultConfigHandsonTable();
	agregarEventoTecladoHandsonTable();
	addRowHandsonTable();
	initDatePicker("#dpFechaEvento");
	listarSedes("#cboSedes");
	$("#btnRegistrarAsistencias").click(registrarAsistencias);
});