let RolesNewController = {
	user: null,
	language: '',
	menus: [],

	reset() {
		let self = this;

		self.user = null;
		self.language = pf.const.language_table;
		self.menus = [];
	},

	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.RSC17 + ' - ' + pf.const.language.RSC7);

		// Opciones de header
		let jsonsubopt = {
			back: 'backRoles',
			save: 'saveRoles'
		};

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

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

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

		// Botones secundarios
		$('#backRoles').addClass('secondary-button');

		// Collapse
		addEventArrowTableHeader();

		self.requestMenus();
		$('#sortableIcons').sortable({
			containment: "#sortableContainer"
		});
		$('#sortableIcons').disableSelection();

		// Recolocar la información de iconos fuera de menú cuando se suelta un elemento
		$("#sortableIcons").droppable({
			drop: function( evento, ui ) {
				$("#iconSeparator").remove();

				setTimeout(function() {
					$('.list-group-item.roles-sec-menu').each(function(index) {
						if(index === 4) {
							$(this).before(`<p id="iconSeparator" class="fs-14 col-font-li ma-bo-10">${pf.const.language.RSC2614}</p>`);
						}
					});
				}, 50);
			}
		});

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

		// Pintar texto de label
		changeLabelsColor();
	},

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

		let arrObj = ['RSC123'];
		pf.rsc.translateByTagHTMLFormat('strong', arrObj);

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

	requestMenus() {
		let self = this;

		ajaxComunCallWithCallback('getCustomMenuAvailableForRole', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				self.menus= ajaxReturn.result;
				self.renderMenus();
			}
		});
	},

	renderMenus() {
		let self = this;
		self.menus.forEach((menu, idx) => {
			let label = menu.option;
			if(menu.type == 'addon') {
				label = menu.name;
			}

			let icon = '';
			if(menu.addon_icon) {
				icon = `<i class="${menu.addon_icon}"></i>`;
			} else {
				switch(menu.option) {
					case 'contacts':
						icon = `<i class="fa-light fa-user-group"></i>`;
						break;
					case 'chats':
						icon = `<i class="fa-light fa-comments"></i>`;
						break;
					case 'calls':
						icon = `<i class="fa-light fa-phone"></i>`;
						break;
					case 'missions':
						icon = `<i class="fa-light fa-clipboard-list-check"></i>`;
						break;
					case 'wallet':
						icon = `<i class="fa-light fa-wallet"></i>`;
						break;
					default:
						icon = `<i class="fa-light fa-magnifying-glass"></i>`;
				}
			}

			if(idx == 4) {
				$('#sortableIcons').append(`<p id="iconSeparator" class="fs-14 col-font-li ma-bo-10">${pf.const.language.RSC2614}</p>`);
			}

			$('#sortableIcons').append(`
				<li class="ui-state-default list-group-item roles-sec-menu he-50 bo-ra-8 ma-bo-10 c-drag" role="button" idRole="${menu.option}" typeRole="${menu.type}">
					<div class="d-flex justify-content-between align-self-center">
						<div class="d-flex align-items-center">
							<svg class="bi bi-list" width="15px" height="15px" fill="currentColor" viewBox="0 0 15 15" xmlns="http://www.w3.org/2000/svg">
								<path fill-rule="evenodd" d="M2.5 12a.5.5 0 0 1 .5-.5h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5zm0-4a.5.5 0 0 1 .5-.5h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5zm0-4a.5.5 0 0 1 .5-.5h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5z"/>
							</svg>

							<span class="iconContainer">${icon}</span>

							<span>${label}</span>
						</div>

						<div class="form-check">
							<input type="radio" class="form-check-input" name="init" ${(idx == 0) ? 'checked' : ''} style="width: 16px; height: 16px;">
						</div>
					</div>
				</li>
			`);
		});

		let sortableContainerHeight = $('#sortableContainer').css('height');
		$('#sortableContainer').css('min-height', sortableContainerHeight);
	},

	applyEvents() {
		let self = this;

		stcmbackend.roles.sharedEvents(self);

		// Restricciones de carácteres por tecla
		$('.ovSpecChars').off().on('keypress', function(e) {
			// Parámetros: tecla, warningTitle, warningContent y pattern si no es el general
			let result = characterRestrictionsPerKey(e.keyCode, pf.const.language.RSC375, pf.const.language.RSC1762);

			return result;
		});

		// Restricciones de carácteres por pegado
		$('.ovSpecChars').on('paste', function() {
			// Parámetros: elemento, warningTitle, warningContent y pattern si no es el general
			characterRestrictionsPerPaste($(this), pf.const.language.RSC375, pf.const.language.RSC1762);
		});

		// Guardar nuevo rol
		$('#saveRoles').on('click', function() {
			let rol = $('#rolName').val().trim();
			if(rol == '') {
				$('#rolName').addClass('is-invalid');
				$('[for="rolName"]').addClass('is-invalid');
				let warningTitle = pf.const.language.RSC17;
				let warningContent = pf.const.language.RSC265;
				pf.utils.showInfoDialog(warningTitle, warningContent);
			} else {
				self.newRole(rol);
			}
		});

		self.rolesTable();
	},

	rolesTable() {
		let self = this;

		let table = stcmbackend.roles.rolesTable();

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

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

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

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

		let dataTable = $('#rolesTable').DataTable({
			retrieve: true,
			language: self.language,
			paging: false,
			ordering: false,
			autoWidth: false,
			columnDefs: [
				{width: '30px', targets: 1}
			],
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC129,
				className: 'd-none',
				title: pf.const.language.RSC224,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}]
		});

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

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

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

		// La id del elemento principal modifica los elementos secundarios a través de su clase
		$('#allSwitchs').on('click', function() {
			$('.uSwitch').prop('checked', this.checked);
		});

		// Si todos los checkbox están seleccionados, se selecciona el checkbox principal, y viceversa
		$('.uSwitch').on('click', function() {
			if($('.uSwitch').length == $('.uSwitch:checked').length) {
				$('#allSwitchs').prop('checked', true);
			} else {
				$('#allSwitchs').prop('checked', false);
			}
		});
	},

	generateMenuArray() {
		let listMenus = $('#sortableIcons li');
		let result = [];
		let valid = true;
		listMenus.each(function(idx, li) {
			let menu = $(li);
			let checked = menu.find('input').is(':checked');
			if(checked && idx > 3) {
				return valid = false;
			}

			let roleString = `${menu.attr('idRole')}#${menu.attr('typeRole')}#${idx}#${(checked)?1:0}`
			result.push(roleString);
		});

		if(!valid) {
			return false;
		}

		return result;
	},

	newRole(rol) {
		let menuArray = this.generateMenuArray();
		if(!menuArray) {
			//error al seleccionar un menú como predeterminado si no está entre los 4 primeros
			pf.utils.showInfoDialog(pf.const.language.RSC1389, pf.const.language.RSC1388);
			return;
		}
		let menusJSON = JSON.stringify(menuArray);
		let permissions = {
			contactsSection: ($('#contactsSection').prop('checked') === true ? 1 : 0),
			addContact: ($('#addContact').prop('checked') === true ? 1 : 0),
			deleteContact: ($('#deleteContact').prop('checked') === true ? 1 : 0),
			newChat: ($('#newChat').prop('checked') === true ? 1 : 0),
			deleteChat: ($('#deleteChat').prop('checked') === true ? 1 : 0),
			createGroup: ($('#createGroup').prop('checked') === true ? 1 : 0),
			doVideocall: ($('#doVideocall').prop('checked') === true ? 1 : 0),
			doVoicecall: ($('#doVoicecall').prop('checked') === true ? 1 : 0),
			writeContact: ($('#writeContact').prop('checked') === true ? 1 : 0),
			sendFilesContact: ($('#sendFilesContact').prop('checked') === true ? 1 : 0),
			sendQuestionContact: ($('#sendQuestionContact').prop('checked') === true ? 1 : 0),
			sendAudioContact: ($('#sendAudioContact').prop('checked') === true ? 1 : 0),
			seeContactProfile: ($('#seeContactProfile').prop('checked') === true ? 1 : 0),
			emptyChatContact: ($('#emptyChatContact').prop('checked') === true ? 1 : 0),
			silenceContact: ($('#silenceContact').prop('checked') === true ? 1 : 0),
			blockContact: ($('#blockContact').prop('checked') === true ? 1 : 0),
			reportSpamContact: ($('#reportSpamContact').prop('checked') === true ? 1 : 0),
			writeGroup: ($('#writeGroup').prop('checked') === true ? 1 : 0),
			sendFilesGroup: ($('#sendFilesGroup').prop('checked') === true ? 1 : 0),
			sendAudioGroup: ($('#sendAudioGroup').prop('checked') === true ? 1 : 0),
			seeGroupDetails: ($('#seeGroupDetails').prop('checked') === true ? 1 : 0),
			emptyChatGroup: ($('#emptyChatGroup').prop('checked') === true ? 1 : 0),
			silenceGroup: ($('#silenceGroup').prop('checked') === true ? 1 : 0),
			leaveGroup: ($('#leaveGroup').prop('checked') === true ? 1 : 0),
			callsSection: ($('#callsSection').prop('checked') === true ? 1 : 0),
			deleteCall: ($('#deleteCall').prop('checked') === true ? 1 : 0),
			seeInfoCall: ($('#seeInfoCall').prop('checked') === true ? 1 : 0),
			configSection: ($('#configSection').prop('checked') === true ? 1 : 0),
			changePhoto: ($('#changePhoto').prop('checked') === true ? 1 : 0),
			changeUsername: ($('#changeUsername').prop('checked') === true ? 1 : 0),
			changeStatus: ($('#changeStatus').prop('checked') === true ? 1 : 0),
			silenceNotificationsContact: ($('#silenceNotificationsContact').prop('checked') === true ? 1 : 0),
			silenceNotificationGroup: ($('#silenceNotificationGroup').prop('checked') === true ? 1 : 0),
			editPassword: ($('#editPassword').prop('checked') === true ? 1 : 0),
			tellFriend: ($('#tellFriend').prop('checked') === true ? 1 : 0),
			termsConditions: ($('#termsConditions').prop('checked') === true ? 1 : 0),
			closeSession: ($('#closeSession').prop('checked') === true ? 1 : 0),
			distributionList: ($('#distributionList').prop('checked') === true ? 1 : 0),
			showClabeAccount: ($('#showClabeAccount').prop('checked') === true ? 1 : 0),
			showWalllet: ($('#showWalllet').prop('checked') === true ? 1 : 0),
			closeQuestion: ($('#closeQuestion').prop('checked') === true ? 1 : 0),
			customIconOrderApp: ($('#editIcons').prop('checked') === true ? 1 : 0),
			customIconSelectApp: ($('#editMainScreen').prop('checked') === true ? 1 : 0),
			showMissionsCenter: ($('#showMissionsCenter').prop('checked') === true ? 1 : 0),
			viewmoreSection: ($('#viewmoreSection').prop('checked') === true ? 1 : 0)
		};

		let parameters = {
			role: rol,
			permissions: JSON.stringify(permissions),
			menus: menusJSON
		};
		ajaxComunCallWithCallback('newRole', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let successTitle = pf.const.language.RSC17;
				let successContent = pf.const.language.RSC266;
				pf.utils.showInfoDialog(successTitle, successContent);
				window.location.href = '#!roles';
			}
		});
	}
};