let AddonsController = {
	data: '',
	arrayDelMult: [],

	reset() {
		let self = this;

		self.data = '';
		self.arrayDelMult = [];
	},

	setEvents() {
		let self = this;
		self.reset();

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

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

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

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

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

		$('#new svg').css({'width': '24px', 'height': '24px'});

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

		ajaxComunCallWithCallback('getAllAddOns', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				self.data = ajaxReturn.response;

				self.renderData();
			}
		});

		self.loadLang();
		self.applyEvents();

		// Collapse
		addEventArrowTableHeader();
	},

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

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

	applyEvents() {
		// Nuevo
		$('#new').on('click', function() {
			window.location.href = '#!addons_new';
		});
	},

	renderData() {
		let self = this;

		let table = `
			<table id="registers" class="table table-hover">
				<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.RSC366}">${pf.const.language.RSC366}</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.RSC550}">${pf.const.language.RSC550}</th>
						<th scope="col" title="${pf.const.language.RSC1247}">${pf.const.language.RSC1247}</th>
						<th scope="col" title="${pf.const.language.RSC355}">${pf.const.language.RSC355}</th>
						<th scope="col" title="${pf.const.language.RSC1248}">${pf.const.language.RSC1248}</th>
						<th scope="col" title="${pf.const.language.RSC1249}">${pf.const.language.RSC1249}</th>
						<th scope="col" title="${pf.const.language.RSC1250}">${pf.const.language.RSC1250}</th>
						<th scope="col" title="${pf.const.language.RSC558}">${pf.const.language.RSC558}</th>
						<th scope="col" title="${pf.const.language.RSC126}">${pf.const.language.RSC126}</th>
						<th scope="col" title="${pf.const.language.RSC1343}">${pf.const.language.RSC1343}</th>
						<th scope="col" title="${pf.const.language.RSC2516}">${pf.const.language.RSC2516}</th>
					</tr>
				</thead>

				<thead class="filtersResult">
					<tr>
						<td>selector</td>
						<td>id</td>
						<td>name</td>
						<td>description</td>
						<td>pais</td>
						<td>path</td>
						<td>url</td>
						<td>function</td>
						<td>params</td>
						<td>var</td>
						<td>registro</td>
						<td>enabled</td>
						<td>icono</td>
						<td>acciones</td>
					</tr>
				</thead>

				<tbody>
		`;

		// Obtener países permitidos
		let allowedCountries = JSON.parse(atob(sessionStorage['STCMBackEnd:userCountries']));

		let size = self.data.length;
		for(let i = 0; i < size; i++) {
			// Control de países permitidos
			if(self.data[i].country != '' && allowedCountries.indexOf(self.data[i].country) == -1) {
				continue;
			}

			table += `
				<tr data-id="${self.data[i].id}">
					<td class="text-center">
						<div class="div-single-selection" data-id="${self.data[i].id}">
							<input type="checkbox" class="deleteSelection">
						</div>
					</td>
					<td class="text-truncate c-pointer editRow" title="${self.data[i].id}">${self.data[i].id}</td>
					<td class="text-truncate c-pointer editRow" title="${self.data[i].addon_name}">${self.data[i].addon_name}</td>
					<td class="text-truncate c-pointer editRow" title="${self.data[i].addon_description}">${self.data[i].addon_description}</td>
					<td class="text-truncate c-pointer editRow" title="${self.data[i].country}">${self.data[i].country}</td>
					<td class="text-truncate c-pointer editRow" title="${self.data[i].addon_path}">${self.data[i].addon_path}</td>
					<td class="text-truncate c-pointer editRow" title="${self.data[i].addon_url}">${self.data[i].addon_url}</td>
					<td class="text-truncate c-pointer editRow" title="${self.data[i].addon_function}">${self.data[i].addon_function}</td>
					<td class="text-truncate c-pointer editRow" title="${self.data[i].addon_function_params}">${self.data[i].addon_function_params}</td>
					<td class="text-truncate c-pointer editRow" title="${self.data[i].addon_var}">${self.data[i].addon_var}</td>
					<td class="text-center c-pointer editRow">
						<span class="d-none">${(self.data[i].enrolamiento == '1' ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<input type="checkbox" class="activa" disabled${(self.data[i].enrolamiento == '1' ? ' checked' : '')}>
					</td>
					<td class="text-center c-pointer editRow">
						<span class="d-none">${(self.data[i].addon_enabled == '1' ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<input type="checkbox" class="activa" disabled${(self.data[i].addon_enabled == '1' ? ' checked' : '')}>
					</td>
					<td class="text-center c-pointer editRow" title="${self.data[i].addon_icon}">
						<i class="${self.data[i].addon_icon}" aria-hidden="true"></i>
					</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="${self.data[i].id}">
							<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
		$('#registers .filtersResult td').each(function() {
			let title = $(this).text();
			let value = `<input type="text" class="form-control form-control-sm">`;

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

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

		let dataTable = $('#registers').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			pageLength: 25,
			autoWidth: false,
			columnDefs: [
				{width: '25px', orderable: false, targets: 0},
				{width: '30px', targets: 1},
				{width: '100px', targets: 2},
				{width: '40px', targets: 4},
				{width: '60px', targets: 10},
				{width: '50px', targets: 11},
				{width: '40px', orderable: false, targets: 12},
				{width: '60px', orderable: false, targets: 13}
			],
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC1246,
				className: 'd-none',
				title: pf.const.language.RSC1246,
				exportOptions: {
					columns: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
				},
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
			aaSorting: []
		});

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

		// Apply the search
		applyTheSearch(dataTable, 'filtersResult');

		// Exportar tabla
		$('#export').off().on('click', function() {
			$('#resultTable .buttons-excel').trigger('click');
		});

		self.tableEvents();

		$('#resultTable').on('draw.dt', function() {
			self.tableEvents();
		});
	},

	tableEvents() {
		let self = this;

		// Eventos del input global
		globalSelectionInputActions();

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

			sessionStorage.setItem('idAddOn', btoa(id));
			window.location.href = '#!addons_edit';
		});

		// Eliminar AddOn
		$('.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.RSC1246;
			let alertText = pf.const.language.RSC1252;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				self.deleteAddOn(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.RSC1246;
			let alertText = pf.const.language.RSC1700;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				self.deleteAddOn();
			}, function() {});
		});
	},

	deleteAddOn(id = false) {
		let self = this;

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

		let parameters = {
			addons: JSON.stringify(addons)
		};
		ajaxComunCallWithCallback('deleteAddOn', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let successTitle = pf.const.language.RSC1246;
				let successContent = pf.const.language.RSC1253;
				pf.utils.showInfoDialog(successTitle, successContent);
				loadHTML('inc/addons/addons.html', 'wrapper', AddonsController);
			}
		});
	}
};