let TenantLicensesController = {
	user: null,
	language: '',
	total: 0,
	data: '',

	reset() {
		let self = this;

		self.user = null;
		self.language = pf.const.language_table;
		self.total = 0;
		self.data = '';
	},

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

		let JSONuser = sessionStorage['STCMBackEnd:user'];
		let user = JSON.parse(JSONuser);
		let userMail = user.email;
		let user_split = userMail.split('@');
		self.user = user_split[0].replace('.', '_');

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

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

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

		let nav = `
			${createSubOptionSave(jsonsubopt.save)}
		`;

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

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

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

		ajaxComunCallWithCallback('getSocialLabsLicencesByTenant', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				self.total = ajaxReturn.result.totalLicences;
				$('#total').text(self.total);
				self.data = ajaxReturn.result.tenants;

				// Tabla de resultados
				self.renderData();
			}
		});

		// Collapse
		addEventArrowTableHeader();
	},

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

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

	applyEvents() {
		let self = this;

		// Guardar
		$('#save').off().on('click', function() {
			self.setSocialLabsLicencesByTenant();
		});
	},

	renderData() {
		let self = this;

		$('#resultTable').show();
		let excelTitle = pf.const.language.RSC1539;

		let table = `
			<thead>
				<tr>
					<th scope="col" title="${pf.const.language.RSC366}">${pf.const.language.RSC366}</th>
					<th scope="col" title="${pf.const.language.RSC1540}">${pf.const.language.RSC1540}</th>
					<th scope="col" title="${pf.const.language.RSC1541}">${pf.const.language.RSC1541}</th>
					<th scope="col" title="${pf.const.language.RSC519}">${pf.const.language.RSC519}</th>
					<th scope="col" title="${pf.const.language.RSC1663}">${pf.const.language.RSC1663}</th>
					<th scope="col" title="${pf.const.language.RSC1664}">${pf.const.language.RSC1664}</th>
				</tr>
			</thead>

			<thead class="filtersResult">
				<tr>
					<td>id</td>
					<td>razonSocial</td>
					<td>nombreComercial</td>
					<td>licencias</td>
					<td>usadas</td>
					<td>libre</td>
				</tr>
			</thead>

			<tbody>
		`;

		let size = self.data.length;
		for(let i = 0; i < size; i++) {
			table += `
				<tr data-index="${i}">
					<td class="text-truncate" title="${self.data[i].idTenant}">${self.data[i].idTenant}</td>
					<td class="text-truncate" title="${self.data[i].razonSocial}">${self.data[i].razonSocial}</td>
					<td class="text-truncate" title="${self.data[i].nombreComercial}">${self.data[i].nombreComercial}</td>
					<td class="text-truncate" title="${(self.data[i].numLicencias || '0')}">
						<span id="licSpan${i}" class="d-none">${(self.data[i].numLicencias || '0')}</span>
						<input id="lic${i}" type="number" class="form-control licInput" value="${(self.data[i].numLicencias || '0')}" title="${(self.data[i].numLicencias || '0')}">
					</td>
					<td class="text-truncate" title="${self.data[i].numLicencesUsed}">${self.data[i].numLicencesUsed}</td>
					<td class="text-truncate" title="${self.data[i].numLicencesFree}">${self.data[i].numLicencesFree}</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

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

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

		let dataTable = $('#registers').DataTable({
			retrieve: true,
			language: self.language,
			pageLength: 25,
			autoWidth: false,
			columnDefs: [
				{width: '30px', targets: 0},
				{width: '70px', targets: 3},
				{width: '60px', targets: 4},
				{width: '60px', targets: 5}
			],
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: excelTitle,
				className: 'd-none',
				title: excelTitle,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}]
		});

		// 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;

		// Modificar el número de licencias
		$('.licInput').off().on('blur', function() {
			let index = $(this).attr('id').replace('lic', '');
			let value = $(this).val();
			$(this).prop('title', value);
			self.data[index].numLicencias = value;
		});
	},

	setSocialLabsLicencesByTenant() {
		let self = this;

		// Comprobación de número de licencias asignadas y creación de array de objetos con los tenants
		let tenants = [];
		let licencias = 0;
		let size = self.data.length;
		for(let i = 0; i < size; i++) {
			licencias += parseInt((self.data[i].numLicencias || 0));

			let obj = {
				idTenant: self.data[i].idTenant,
				numLicencias: (self.data[i].numLicencias || '0')
			};

			tenants.push(obj);
		}
		if(self.total < licencias) {
			let warningTitle = pf.const.language.RSC1539;
			let warningContent = pf.const.language.RSC1666;
			pf.utils.showInfoDialog(warningTitle, warningContent);
			return;
		}

		let parameters = {
			tenants: JSON.stringify(tenants)
		};
		ajaxComunCallWithCallback('setSocialLabsLicencesByTenant', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let successTitle = pf.const.language.RSC1539;
				let successContent = pf.const.language.RSC1668;
				pf.utils.showInfoDialog(successTitle, successContent);

				loadHTML('inc/multiTenant/tenant_licenses.html', 'wrapper', TenantLicensesController);
			}
		});
	}
};