let DominiosEmbebidosController = {
	domains: null,
	domainValue: '',
	arrayDelMult: [],

	setEvents() {
		let self = DominiosEmbebidosController;

		// Reducción de Header
		headerSectionHeight(0);

		// Añadir titulo
		$('#page-title').text(pf.const.language.RSC42);

		// Opciones de header
		let jsonsubopt = {
			new: 'btn-send'
		};

		let nav = `
			${createSubOptionNew(jsonsubopt.new)}
		`;

		// Acciones de página (flex-row-reverse)s
		$('#page-actions').html(nav);

		$('#btn-send svg').css('width', '24px');
		$('#btn-send svg').css('height', '24px');

		// Botón principal
		$('#btn-send').addClass('main-button');

		self.loadLanguage();

		ajaxComunCallWithCallback('getAllDomains', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				// Comprobación de array
				if(!Array.isArray(ajaxReturn.result)) self.domains = [];
				else self.domains = ajaxReturn.result;
				self.renderDomains();
			}
		});

		$('#btn-send').click(function() {
			window.location.href = '#!dominios_embebidos_new';
		});

		// Collapse
		addEventArrowTableHeader();
	},

	loadLanguage() {
		pf.rsc.translateByTag('text');

		// TITLES
		$('.deleteMultTitle').attr('title', pf.const.language.RSC95);
	},

	renderDomains() {
		let self = this;

		let table = `
			<table id="tableProfiles" class="table table-hover 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.RSC555}">${pf.const.language.RSC555}</th>
						<th scope="col" title="${pf.const.language.RSC2516}">${pf.const.language.RSC2516}</th>
					</tr>
				</thead>

				<thead class="filtersProfiles">
					<tr>
						<td>selector</td>
						<td>bots</td>
						<td>acciones</td>
					</tr>
				</thead>

				<tbody>
		`;

		let size = self.domains.length;
		for(let i = 0; i < size; i++) {
			table += `
				<tr data-id="${i}">
					<td class="text-center">
						<div class="div-single-selection" data-id="${i}">
							<input type="checkbox" class="deleteSelection">
						</div>
					</td>
					<td class="text-truncate c-pointer editRow" title="${self.domains[i].domain}">${(self.domains[i].domain != '' ? self.domains[i].domain : '-')}</td>
					<td class="text-center">
						<div id="dropdownActions${i}" class="div-dd-actions c-pointer" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
							${stcmbackend.svg.threeDotsVertical18}
						</div>

						<div class="dropdown-menu dropdown-menu-right shadow menu-actions" aria-labelledby="dropdownActions${i}" data-id="${i}">
							<p class="dropdown-item editRow">
								${stcmbackend.svg.pencilWithoutColor}
								<span>${pf.const.language.RSC225}</span>
							</p>
							<p class="dropdown-item deleteRow">
								${stcmbackend.svg.trashWithoutColor}
								<span>${pf.const.language.RSC95}</span>
							</p>
						</div>
					</td>
				</tr>
			`;
		}

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

		$('#resultTable').html(table);

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

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

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

		let tableProfiles = $('#tableProfiles').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			pageLength: 25,
			columnDefs: [
				{width: '25px', orderable: false, targets: 0},
				{width: '60px', orderable: false, targets: 2}
			],
			scrollCollapse: true,
			scroller: false,
			paging: true,
			autoWidth: false,
			aaSorting: [],
			lengthChange: false,
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC42,
				className: 'btn secondary-button ma-le-5',
				title: pf.const.language.RSC42,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}]
		});

		$('.dataTables_filter').hide();

		$('#btn-actions').html(tableProfiles.buttons().container());

		// Dar estilo al boton de excel
		$('.buttons-excel').removeClass('btn-secondary');
		$('.buttons-excel').attr('title', pf.const.language.RSC47);

		$('.buttons-excel').html(
			stcmbackend.svg.download + 
			`<span>${pf.const.language.RSC47}</span>`
		);

		// Apply the search
		applyTheSearch(tableProfiles, 'filtersProfiles');

		// Eventos
		self.applyEventsTable(tableProfiles);

		$('#tableProfiles').on('draw.dt', function() {
			self.applyEventsTable(tableProfiles);
		});
	},

	applyEventsTable(dataTable) {
		let self = this;

		// Eventos del input global
		globalSelectionInputActions();

		// Editar dominio
		$('.editRow').off().on('click', function() {
			let id = $(this).parent().data('id');

			sessionStorage.setItem('domain', btoa(JSON.stringify(self.domains[id])));
			window.location.href = '#!dominios_embebidos_edit';
		});

		// Eliminar dominio
		$('.deleteRow').off().on('click', function() {
			let id = $(this).parent().data('id');

			let objInfo = {
				accept: {
					text: pf.const.language.RSC95
				},
				cancel: {
					text: pf.const.language.RSC57
				}
			};

			let alertTitle = pf.const.language.RSC42;
			let alertText = pf.const.language.RSC108;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				self.removeDomain(id);
			}, function() {});
		});

		// Array de eliminado múltiple
		$('.deleteSelection').off().on('change', function() {
			let value = $(this).prop('checked');
			let id = $(this).parent().data('id');

			if(value) {
				self.arrayDelMult.push(id);
			} else {
				let index = self.arrayDelMult.indexOf(id);
				self.arrayDelMult.splice(index, 1);
			}

			// Eventos de los inputs individuales
			deleteSelectionInputActions(self.arrayDelMult);
		});

		// Función de borrado múltiple
		$('#multSelecDelete').off().on('click', function() {
			// Aviso de borrado múltiple
			let objInfo = {
				accept: {
					text: pf.const.language.RSC95
				},
				cancel: {
					text: pf.const.language.RSC57
				}
			};

			let alertTitle = pf.const.language.RSC42;
			let alertText = pf.const.language.RSC1702;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				self.removeDomain();
			}, function() {});
		});
	},

	removeDomain(id = false) {
		let self = DominiosEmbebidosController;

		let domains = [];
		if(id !== false) {
			let obj = {
				id: self.domains[id].domain
			}
			domains.push(obj);
		} else {
			let delSize = self.arrayDelMult.length;
			for(let i = 0; i < delSize; i++) {
				let obj = {
					id: self.domains[self.arrayDelMult[i]].domain
				}
				domains.push(obj);
			}
			self.arrayDelMult = [];
		}

		let parameters = {
			domains: JSON.stringify(domains)
		};
		ajaxComunCallWithCallback('deleteDomain', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let errorTitle = pf.const.language.RSC95;
				let errorContent = pf.const.language.RSC96;
				pf.utils.showInfoDialog(errorTitle, errorContent);
				loadHTML('inc/configuracion/dominios_embebidos.html', 'wrapper', DominiosEmbebidosController);
			}
		});
	}
};