class TableProducts {
	constructor(type = 0, actions) {
		this.type = type;
		this.actionsTable = actions;
		this.data = null;
		this.products = [];
		this.modality = null;
	}

	setEvents(products = [], modality = 'tableModal') {
		let self = this;

		self.modality = modality;

		if(products.length > 0) {
			self.products = products;
		}

		if(self.data) {
			self.renderTable();
		} else {
			self.requestProducts();
		}
	}

	requestProducts() {
		let self = this;

		clearGeneralModal();

		ajaxComunCallWithCallback('getAllProducts', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				self.data = ajaxReturn.result;
				self.renderTable();
			}
		});
	}

	renderTable() {
		let self = this;

		let headerCheckbox = '';
		let filterCheckbox = '';

		// Si la tabla de modal es de selección múltiple
		if(self.type === 1) {
			headerCheckbox = `
				<th class="text-center" scope="col" title="">
					<div class="div-global-selection">
						<input type="checkbox" class="globalSelection">
					</div>
				</th>
			`;

			filterCheckbox = `<td>selector</td>`;

			let acceptButton = `
				<button id="selectProducts" 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="${self.modality}" class="table table-hover tRegs">
					<thead>
					<tr>
						${headerCheckbox}
						<th scope="col" title="${pf.const.language.RSC437}">${pf.const.language.RSC437}</th>
						<th scope="col" title="${pf.const.language.RSC123}">${pf.const.language.RSC123}</th>
						<th scope="col" title="${pf.const.language.RSC178}">${pf.const.language.RSC178}</th>
						<th scope="col" title="${pf.const.language.RSC1046}">${pf.const.language.RSC1046}</th>
					</tr>
				</thead>

				<thead class="filtersProduct">
					<tr>
						${filterCheckbox}
						<td>code</td>
						<td>name</td>
						<td>description</td>
						<td>packaging</td>
					</tr>
				</thead>

				<tbody>
		`;

		let size = self.data.length;
		for(let i = 0; i < size; i++) {
			let bodyCheckbox = '';

			// Si la tabla de modal es de selección múltiple
			if(self.type === 1) {
				let checked = '';
				for(let j = 0; j < self.products.length; j++) {
					if(self.products[j].code == self.data[i].code) {
						checked = 'checked';
					}
				}

				bodyCheckbox = `
					<td class="text-center">
						<div class="div-single-selection">
							<input type="checkbox" class="selection" ${checked}>
						</div>
					</td>
				`;
			}

			table += `
				<tr id="code${self.data[i].code}" class="user_selected" unity="${self.data[i].packaging}" data-id="${i}">
					${bodyCheckbox}
					<td class="text-truncate" title="${self.data[i].code}">${self.data[i].code}</td>
					<td class="text-truncate" title="${self.data[i].name}">${self.data[i].name}</td>
					<td class="text-truncate" title="${self.data[i].description}">${self.data[i].description}</td>
					<td class="text-truncate" title="${self.data[i].packaging}">${self.data[i].packaging}</td>
				</tr>
			`;
		}

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

		if(this.modality == 'tableModal') {
			$('#headerModalTitle').text(pf.const.language.RSC1047);
			$('#divTableModal').html(table);
		} else {
			$('#div' + this.modality).html(table);
		}

		// Setup - add a text input to each footer cell
		$('#' + this.modality + ' .filtersProduct 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 scroll = 300;
		if(self.modality != 'tableModal') {
			scroll = 600;
		}

		let columnDefs = [];
		if(self.type === 1) {
			columnDefs = [{width: '25px', orderable: false, targets: 0}];
		}

		let tableUsers = $('#' + this.modality).DataTable({
			language: pf.const.language_table,
			scrollY: scroll,
			scroller: false,
			paging: true,
			pageLength: 25,
			autoWidth: false,
			columnDefs: columnDefs,
			aaSorting: []
		});

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

		// Ocultar botones de tabla
		hideTableButtons(this.modality);

		// Apply the search
		applyTheSearch(tableUsers, 'filtersProduct');

		if(self.type === 0) {
			// Detectar click
			$('#' + this.modality + ' tbody').off().on('click', 'tr', function() {
				self.eventsTable($(this).data('id'));
				$('#closeUser').trigger('click');
			});
		} else {
			self.multiSelectTableEvents();

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

			// Selección de múltiples productos
			$('#selectProducts').off().on('click', function() {
				addLoader();
				let p = [];
				let positionMember = '';
				self.products = [];
				$('#tableModal tr').each(function() {
					let cheked = $(this).find('.selection');
					if(cheked.prop('checked')) {
						positionMember = $(this).data('id');
						self.products.push(self.data[positionMember]);
						p.push(self.data[positionMember])
					}
				});
				tableUsers.destroy();
				self.eventsTable(0, p);
				removeLoader();
				$('#closeUser').trigger('click');
			});
		}
	}

	multiSelectTableEvents() {
		inputControl();

		// 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);
			} else {
				$(this).find('.selection').prop('checked', true);
			}

			inputControl();
		});

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

			inputControl();
		});

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

		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);
			}
		}
	}

	eventsTable(id, products) {
		let self = this;

		let response = '';
		if(self.type === 0) {
			response = self.data[id];
		} else {
			response = products;
		}

		switch(self.actionsTable) {
			case 'addProducts':
				MisionesNewController.clickEvents(response);
				break;
			case 'addProductsEdit':
				MisionesEditController.clickEvents(response);
				break;
			case 'StepByStepMissionNewController':
				StepByStepMissionNewController.clickEvents(response);
				break;
			case 'StepByStepMissionEditController':
				StepByStepMissionEditController.clickEvents(response);
				break;
		}
	}
}