class TableRotation {
	constructor(actions, params) {
		this.actionsTable = actions;
		this.allRotations = null;
		this.survey = params.survey,
		this.mision = params.mision,
		this.project = params.project,
		this.surname = true;
		this.deleteOriginal = false;
		this.updated = true;
	};

	setEvents() {
		let self = this;

		self.requestAllRotacionesSurvey();
	};

	requestAllRotacionesSurvey() {
		let self = this;

		clearGeneralModal();

		let parameters = {
			survey: this.survey
		};
		ajaxComunCallWithCallback('getAllRotacionesSurvey', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.allRotations = ajaxReturn.result;
				self.requestProjectRotationes();
			}
		});
	}

	requestProjectRotationes() {
		let self = this;

		let parameters = {
			survey: this.survey,
			mision: this.mision,
			idProject: this.project
		};
		ajaxComunCallWithCallback('getProjectMisionRotaciones', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.selectedRotations = ajaxReturn.result;

				if(self.selectedRotations.length != 0) {
					self.deleteOriginal = true;
				}
				self.renderTable();
			}
		});
	}

	renderTable() {
		let self = this;

		let acceptButton = `
			<button id="selectRotations" type="button" class="btn main-button" title="${pf.const.language.RSC141}">
				<span>${pf.const.language.RSC141}</span>
			</button>
		`;

		$('#divModalFooter').html(acceptButton);

		let table = `
			<table id="tableModal" class="table table-hover tr-pointer tRegs">
				<thead>
					<tr>
						<th class="text-center" scope="col" title="">
							<div class="div-global-selection">
								<input type="checkbox" class="globalSelection">
							</div>
						</th>
						<th scope="col" title="${pf.const.language.RSC1405}">${pf.const.language.RSC1405}</th>
						<th scope="col" title="${pf.const.language.RSC178}">${pf.const.language.RSC178}</th>
						<th scope="col" title="${pf.const.language.RSC520}">${pf.const.language.RSC520}</th>
					</tr>
				</thead>

				<thead class="filtersRotation">
					<tr>
						<td>selector</td>
						<td>IDRotacion</td>
						<td>Description</td>
						<td>Percent</td>
					</tr>
				</thead>

				<tbody>
		`;

		let size = self.allRotations.length;
		for(let i = 0; i < size; i++) {
			//let bodyCheckbox = '';
			let disabled = 'disabled';
			let percent = '';
			let checked = '';

			for(let j = 0; j < self.selectedRotations.length; j++) {
				if(self.selectedRotations[j].idrotation == self.allRotations[i].idrotation) {
					checked = 'checked';
					disabled = '';
					percent = self.selectedRotations[j].porcentaje;
				}
			}

			table += `
				<tr id="${self.allRotations[i].idrotation}" class="c-auto" data-id="${i}">
					<td class="text-center">
						<div class="div-single-selection">
							<input type="checkbox" class="selection rotationCheckbox" ${checked}>
						</div>
					</td>
					<td class="text-truncate" title="${self.allRotations[i].idrotation}">${self.allRotations[i].idrotation}</td>
					<td class="text-truncate" title="${self.allRotations[i].description}">${self.allRotations[i].description}</td>
					<td>
						<input id="input_${i}" type="text" class="form-control rotationPercent" aria-label="Small" aria-describedby="inputGroup-sizing-sm" placeholder="%" value="${percent}" ${disabled}>
					</td>
				</tr>
			`;
		}

		table += `
				</tbody>
			</table>
		`;

		$('#headerModalTitle').text(pf.const.language.RSC1404);
		$('#divTableModal').html(table);

		// Setup - add a text input to each footer cell
		$('#divTableModal .filtersRotation td').each(function() {
			let title = $(this).text();
			let value = `<input type="text" class="form-control form-control-sm">`;

			if(title == 'selector') {
				value = `<input type="text" class="form-control form-control-sm" disabled>`;
			}

			$(this).html(value);
		});

		let tableRotations = $('#tableModal').DataTable({
			language: pf.const.language_table,
			scrollY: 300,
			scroller: false,
			paging: true,
			pageLength: 25,
			autoWidth: false,
			columnDefs: [
				{width: '25px', orderable: false, targets: 0}
			],
			aaSorting: []
		});

		setTimeout(function() {
			tableRotations.columns.adjust();
		}, 200);

		// Ocultar botones de tabla
		hideTableButtons('tableModal');

		// Apply the search
		applyTheSearch(tableRotations, 'filtersRotation');

		self.multiSelectTableEvents();

		$('#tableModal').on('draw.dt', function() {
			self.multiSelectTableEvents();
		});

		// Selección de múltiples rotaciones
		$('#selectRotations').off().on('click', function() {
			let rotationArray = self.getSelectedRotations();
			if(!rotationArray) {
				pf.utils.showInfoDialog(pf.const.language.RSC1451, pf.const.language.RSC1452);
				removeLoader();
			} else {
				$('#closeUser').trigger('click');
				self.eventsTable(rotationArray);
				removeLoader();
			}
		});
	}

	multiSelectTableEvents() {
		inputControl();

		// Para que no se propague el click del input
		$('.rotationPercent').off().on('click', function(event) {
			event.stopPropagation();
		});

		// Selección por tr
		$('#tableModal tbody tr').off().on('click', function() {
			let checkedComp = $(this).find('.selection').prop('checked');
			if(checkedComp) {
				$(this).find('.selection').prop('checked', false);
				$(this).find('.rotationPercent').val('');
				$(this).find('.rotationPercent').prop('disabled', true);
			} else {
				$(this).find('.selection').prop('checked', true);
				$(this).find('.rotationPercent').prop('disabled', false);
			}

			inputControl();
		});

		// Selección por input check
		$('.selection').off().on('click', function() {
			let checkedComp = $(this).prop('checked');
			if(checkedComp) {
				$(this).prop('checked', false);
				$(this).parent().parent().parent().find('.rotationPercent').val('');
				$(this).parent().parent().parent().find('.rotationPercent').prop('disabled', true);
			} else {
				$(this).prop('checked', true);
				$(this).parent().parent().parent().find('.rotationPercent').prop('disabled', false);
			}

			inputControl();
		});

		// Marcar desmarcar todo
		$('.globalSelection').off().on('change', function() {
			if($('.globalSelection').prop('checked')) {
				$('.selection').prop('checked', true);
				$('.rotationPercent').prop('disabled', false);
			} else {
				$('.selection').prop('checked', false);
				$('.rotationPercent').val('');
				$('.rotationPercent').prop('disabled', true);
			}
		});

		function inputControl() {
			// Estado del input global con respecto a los inputs en página
			if($('.selection').length == $('.selection:checked').length && $('.selection').length > 0) {
				$('.globalSelection').prop('checked', true);
			} else {
				$('.globalSelection').prop('checked', false);
			}
		}
	}

	getSelectedRotations() {
		let self = this;

		addLoader();
		self.rotations = [];
		let rotationArray = [];
		let index = '';
		$('#tableModal tbody tr').each(function() {
			let cheked = $(this).find('.selection');
			let percent = $(this).find('.rotationPercent');
			let rot = $(this);

			if(cheked.prop('checked')) {
				let percentValue= percent.val();
				index = $(this).data('id');
				let rotation = {
					...self.allRotations[index],
					porcentaje: percentValue
				}
				self.rotations.push(rotation);
				let rotationString = `${self.project}#${self.mision}#${self.allRotations[index].idrotation}#${self.survey}#${percentValue}`;
				rotationArray.push(rotationString);
			} else {
				index = $(this).data('id');
				let rotationString = `${self.project}#${self.mision}#${self.allRotations[index].idrotation}#${self.survey}#0`;
				rotationArray.push(rotationString);
			}
		});

		return(self.validatePercent(rotationArray));
	}

	validatePercent(rotationArray) {
		let self = this;

		let total = 0;
		self.rotations.forEach(rotation => {
			total += parseInt(rotation.porcentaje);
		});
		if(total !== 100) {
			return false
		}
		return(rotationArray);
	}

	generateRotationArray() {
		let self = this;

		let rotationArray = [];
		self.rotations.forEach(rotation => {
			let rotationString = `${self.project}#${self.mision}#${rotation.idrotation}#${self.survey}#${rotation.porcentaje}`;
			rotationArray.push(rotationString);
		});
		return rotationArray;
	}

	eventsTable(rotationArray) {
		let self = this;

		switch(self.actionsTable) {
			case 'editProject':
				ProyectosEditController.addRotationToMision(self.mision, rotationArray, self.rotations);
				break;
		}
	}
}