stcmbackend.grupos = {
	sharedEvents(self) {
		$('#backLists').on('click', function() {
			window.location.href = '#!grupos';
		});

		$('#btn-send').click(function() {
			// Comprobar que los campos esta rellenos
			if($('#SYSNotifUser').text().length == 0 || $('#groupName').val().length == 0 || self.members.length == 0) {
				if($('#groupName').val().length == 0) {
					$('#groupName').addClass('is-invalid');
					$('[for="groupName"]').addClass('is-invalid');
				}
				if($('#SYSNotifUser').text().length == 0) {
					$('#SYSNotifUserName').addClass('is-invalid');
					$('#SYSNotifUserName-group').addClass('group-invalid');
					$('[for="SYSNotifUserName"]').addClass('is-invalid');
				}
				if(self.members.length == 0) {
					$('#membersSelect').addClass('is-invalid');
					$('#membersSelect-group').addClass('group-invalid');
					$('[for="membersSelect"]').addClass('is-invalid');
				}

				pf.utils.alerts.showCompleteAllFields();
			} else {
				$('#groupName').removeClass('is-invalid');
				$('[for="groupName"]').removeClass('is-invalid');
				$('#SYSNotifUserName').removeClass('is-invalid');
				$('#SYSNotifUserName-group').removeClass('group-invalid');
				$('[for="SYSNotifUserName"]').removeClass('is-invalid');
				$('#membersSelect').removeClass('is-invalid');
				$('#membersSelect-group').removeClass('group-invalid');
				$('[for="membersSelect"]').removeClass('is-invalid');

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

				let alertTitle = pf.const.language.RSC78;
				let alertText = pf.const.language.RSC105;
				pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
					self.sendGroup();
				}, function() {});
			}
		});

		// Ocultar cubo de basura
		$('#countryDelete').hide();

		// Limpiar País
		$('#countryDelete').on('click', function() {
			$('#pais').val('');
			self.countryFilter = '';
			self.adminModal.admin = null;
			self.adminModal.data = null;
			self.adminModal.country = self.countryFilter;
			self.crewObject.data = null;
			self.crewObject.country = self.countryFilter;
			self.userBot.data = null;
			self.userBot.country = self.countryFilter;
			self.userNotif.data = null;
			self.userNotif.country = self.countryFilter;
			$('#countryDelete').hide();
		});

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

		// Collapse
		addEventArrowTableHeader();

		// Importar excel
		$('#import').click(function() {
			$('#inputFile').trigger('click');
		})

		// Detectar fichero subido
		$('#inputFile').change(function(evt) {
			stcmbackend.grupos.uploadFile(evt, self);
		});
	},

	uploadFile(evt, self) {
		let selectedFile = evt.target.files[0];
		let reader = new FileReader();
		addLoader();

		reader.onload = function(event) {
			let data = event.target.result;
			let workbook = XLSX.read(data, {
				type: 'binary'
			});

			workbook.SheetNames.forEach(function(sheetName) {
				let arrayRSC = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
				let newMembers = [];
				let sizeNew = arrayRSC.length;
				for(let i = 0; i < sizeNew; i++) {
					let name = 'name' + (i + 1);
					let mail = 'mail' + (i + 1);
					if(arrayRSC[i].Nombre) {
						name = arrayRSC[i].Nombre.trim();
					}
					if(arrayRSC[i]['E-mail']) {
						mail = arrayRSC[i]['E-mail'].trim();
					}

					let objNew = {
						nameUser: name,
						email: mail,
						id: ''
					};
					newMembers.push(objNew);
				}

				addLoader();
				stcmbackend.grupos.setMembers(newMembers, self);
			});
		};

		// reader.onerror = function(event) {
		// 	console.error('File could not be read! Code ' + event.target.error.code);
		// };

		reader.readAsBinaryString(selectedFile);
	},

	setMembers(newMembers, self) {
		ajaxComunCallWithCallback('getDomain', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				for(let i = 0; i < newMembers.length; ++i) {
					//build id for each member
					newMembers[i].id = newMembers[i].email.replace('@', '.') + '@' + ajaxReturn.result[0];
				}

				stcmbackend.grupos.getAllUsers(newMembers, self);
				removeLoader();
			}
		}, false);
	},

	getAllUsers(newMembers, self) {
		let parameters = {
			country: self.countryFilter,
			consejero: 1,
			enabled: 1,
			staff: 1
		};
		ajaxComunCallWithCallback('getAllUsers', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				// Array de usuarios
				let usersIDArray = [];
				let size = ajaxReturn.result.length;
				for(let i = 0; i < size; i++) {
					usersIDArray.push(ajaxReturn.result[i].id);
				}

				// Comprobación de usuarios a añadir al grupo
				self.members = [];
				let gSize = newMembers.length;
				for(let i = 0; i < gSize; i++) {
					if(usersIDArray.indexOf(newMembers[i].id) !== -1) {
						self.members.push(newMembers[i]);
					}
				}

				self.crewObject.members = self.members;
				tableMembers.setEvents(self.crewObject.members, 'tableMembersUsers', 'editGroups');

				removeLoader();
			}
		}, false);
	}
};