let BotsController = {
	bots: null,
	botName: '',
	directLine: '',
	arrayDelMult: [],

	setEvents() {
		let self = BotsController;

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

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

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

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

		self.getBots();

		// Collapse
		addEventArrowTableHeader();
	},

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

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

	getBots() {
		let self = BotsController;

		ajaxComunCallWithCallback('getAllBots', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				self.bots = ajaxReturn.result;

				self.renderBots();
			}
		});
	},

	renderBots() {
		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.RSC99}">${pf.const.language.RSC99}</th>
						<th scope="col" title="${pf.const.language.RSC98}">${pf.const.language.RSC98}</th>
						<th scope="col" title="${pf.const.language.RSC550}">${pf.const.language.RSC550}</th>
						<th scope="col" title="${pf.const.language.RSC2516}">${pf.const.language.RSC2516}</th>
					</tr>
				</thead>

				<thead class="filtersProfiles">
					<tr>
						<td>selector</td>
						<td>botname</td>
						<td>directLine</td>
						<td>pais</td>
						<td>acciones</td>
					</tr>
				</thead>

				<tbody>
		`;

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

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

			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.bots[i].botName}">${(self.bots[i].botName != '' ? self.bots[i].botName : '-')}</td>
					<td class="text-truncate c-pointer editRow" title="${self.bots[i].directLine}">${(self.bots[i].directLine != '' ? self.bots[i].directLine : '-')}</td>
					<td class="text-truncate c-pointer editRow" title="${self.bots[i].pais}">${(self.bots[i].pais != '' ? self.bots[i].pais : '-')}</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: '50px', targets: 3},
				{width: '60px', orderable: false, targets: 4}
			],
			scrollCollapse: true,
			scroller: false,
			paging: true,
			autoWidth: false,
			aaSorting: [],
			lengthChange: false,
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC43,
				className: 'btn secondary-button ma-le-5',
				title: pf.const.language.RSC43,
				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 bot
		$('.editRow').off().on('click', function() {
			let id = $(this).parent().data('id');

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

		// Eliminar bot
		$('.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.RSC43;
			let alertText = pf.const.language.RSC104;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				self.removeBot(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.RSC43;
			let alertText = pf.const.language.RSC1703;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				self.removeBot();
			}, function() {});
		});
	},

	removeBot(id = false) {
		let self = BotsController;

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

		let parameters = {
			bots: JSON.stringify(bots)
		};
		ajaxComunCallWithCallback('deleteBot', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let errorTitle = pf.const.language.RSC95;
				let errorContent = pf.const.language.RSC102;
				pf.utils.showInfoDialog(errorTitle, errorContent);

				loadHTML('inc/configuracion/bots.html', 'wrapper', BotsController);
			}
		});
	}
};