let GruposEditarController = {
	users: null,
	config: null,
	token: null,
	members: null,
	admin: null,
	bots: null,
	userType: null,
	group: null,
	groupData: null,
	botConfig: null,
	userClick: null,
	crewObject: null,
	isEditName: 0,
	isEditAdmin: false,
	isEditBot: 0,
	membersOld: null,
	adminModal: null,
	userBot: null,
	userNotif: null,
	countryFilter: '',

	resetData() {
		let self = GruposEditarController;

		self.users = null;
		self.config = null;
		self.token = sessionStorage['STCMBackEnd:token'];
		self.members = [];
		self.bots = null;
		self.userType = null;
		self.groupData = null;
		self.admin = null;
		self.isEditName = 0;
		self.isEditAdmin = 0;
		self.isEditBot = 0;
		self.membersOld = [];
		self.group = {
			nameAdmin: null,
			idAdmin: null,
			groupName: null,
			country: null
		};
		self.botConfig = {
			idUserOrGroup: null,
			directLineSecret: null,
			botId: null,
			isGroup: null,
			enabled: null,
			botUser: null,
			numVecesNoMatch: null,
			textoNoMatch: null,
			userNotificarNoMatch: null,
			textoNotificarNoMatch: null,
			saludoInicial: null
		};
		self.adminModal = null;
		self.crewObject = null;
		self.userBot = null;
		self.userNotif = null;
		self.countryFilter = '';
	},

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

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

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

		// Opciones de header
		let jsonsubopt = {
			back: 'backLists',
			save: 'btn-send'
		};

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

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

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

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

		self.loadLanguage();

		// Obtener grupo a editar
		let group = sessionStorage['STCMBackEnd:editGroup'];
		self.groupData = JSON.parse(atob(group));
		self.group.groupName = self.groupData.name;
		self.group.country = self.groupData.country;
		self.countryFilter = self.groupData.country;

		addLoader();
		self.getMembers();

		stcmbackend.grupos.sharedEvents(self);

		$('#groupName').change(function() {
			self.isEditName = 1;
		});

		// Detectar cambio bots config
		$('#directLineSecret').change(function() {
			self.isEditBot = 1;
		});
		$('#botId').change(function() {
			self.isEditBot = 1;
		});
		$('#enabled').change(function() {
			self.isEditBot = 1;
		});
		$('#botUser').change(function() {
			self.isEditBot = 1;
		});
		$('#numVecesNoMatch').change(function() {
			self.isEditBot = 1;
		});
		$('#textoNoMatch').change(function() {
			self.isEditBot = 1;
		});
		$('#userNotificarNoMatch').change(function() {
			self.isEditBot = 1;
		});
		$('#textoNotificarNoMatch').change(function() {
			self.isEditBot = 1;
		});
		$('#saludoInicial').change(function() {
			self.isEditBot = 1;
		});

		// País
		let countryModal = new TableCountries(0, 'editGroupCountry');
		$('#searchCountry').off().on('click', function() {
			self.userType = 'country';
			countryModal.setEvents();
		});

		// Cargar usuarios admin
		self.adminModal = new TableUsers(0, 'editGroups', self.countryFilter, 1, 1, 1);
		self.adminModal.surname = false;
		$('#btn-users').click(function() {
			self.userType = 'adminGroup';
			self.adminModal.setEvents('tableModal');
		});

		// Cargar usuarios para añadir al grupo
		self.crewObject = new TableUsers(1, 'editGroups', self.countryFilter, 1, 1, 1);
		self.crewObject.members = self.members;
		self.crewObject.surname = false;
		$('#btn-addUser').click(function() {
			self.userType = 'addMembers';
			self.crewObject.setEvents();
		});

		// Cargar usuarios bot user
		self.userBot = new TableUsers(0, 'editGroups', self.countryFilter);
		$('#btn-botUser').click(function() {
			self.userType = 'userBot';
			self.userBot.setEvents();
		});

		// Cargar usuarios notificacion
		self.userNotif = new TableUsers(0, 'editGroups', self.countryFilter);
		$('#btn-userNotificarNoMatch').click(function() {
			self.userType = 'userNotif';
			self.userNotif.setEvents();
		});

		$('#btn-bots').click(function() {
			self.userType = 'bots';
			tableBots.setEvents('editGroups');
		});

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

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

		let arrObj = ['RSC300'];
		pf.rsc.translateByTagHTMLFormat('simple', arrObj);
	},

	getMembers() {
		let self = GruposEditarController;

		let parameters = {
			groupId: self.groupData.idGroup
		};
		ajaxComunCallWithCallback('getAllUsersGroup', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				for(let i = 0; i < ajaxReturn.result.length; i++) {
					if(ajaxReturn.result[i].Admin == 1) {
						self.group.nameAdmin = ajaxReturn.result[i].name;
						self.group.idAdmin = ajaxReturn.result[i].jidUser;
					} else {
						let member = {
							email: ajaxReturn.result[i].email,
							id: ajaxReturn.result[i].jidUser,
							nameUser: ajaxReturn.result[i].userNombre || ajaxReturn.result[i].name,
							userApellidos: ajaxReturn.result[i].userApellidos || '',
							userApellidos2: ajaxReturn.result[i].userApellidos2 || ''
						}
						self.members.push(member);
						self.membersOld.push(member);
					}
				}

				self.getBotConfig();
			}
		}, false);
	},

	getBotConfig() {
		let self = GruposEditarController;

		let parameters = {
			idUserOrGroup: self.groupData.groupName,
			isGroup: 1
		};
		ajaxComunCallWithCallbackOne('getBotConfig', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let resp = JSON.parse(ajaxReturn.resData.response);
				if(resp.result == 'Not authorized') {
					pf.ajax.setWindowLocationIndex();
				} else {
					self.botConfig = resp.result[0];
					self.setInputs();
				}

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

	setInputs() {
		let self = this;

		// Buscar nombre administrador de grupo
		let adminName = '';
		for(let i = 0; i < self.members.length; i++) {
			if(self.group.groupAdmin == self.members[i].id) {
				adminName = self.members[i].nameUser;
			}
		}

		//Groups
		$('#SYSNotifUser').text(self.group.idAdmin);
		$('#SYSNotifUserName').val(self.group.nameAdmin);
		$('#groupName').val(self.group.groupName);
		$('#pais').val(self.group.country);
		if(self.group.country != '') {
			$('#countryDelete').show();
		}
		tableMembers.setEvents(self.members, 'tableMembersUsers', 'editGroups');

		//Bots
		if(self.botConfig) {
			$('#directLineSecret').val(self.botConfig.directLineSecret);
			$('#botId').val(self.botConfig.botId);
			$('#botUser').val(self.botConfig.botUser);
			$('#numVecesNoMatch').val(self.botConfig.numVecesNoMatch);
			$('#textoNoMatch').val(self.botConfig.textoNoMatch);
			$('#userNotificarNoMatch').val(self.botConfig.userNotificarNoMatch);
			$('#textoNotificarNoMatch').val(self.botConfig.textoNotificarNoMatch);

			if(self.botConfig.enabled == 1) {
				$('#enabled').prop('checked', true);
			}
			if(self.botConfig.saludoInicial == 1) {
				$('#saludoInicial').prop('checked', true);
			}
		}
	},

	// Seleccionar usuario de la lista
	addUserGroup(i) {
		let self = GruposEditarController;

		self.members.push(self.users[i]);
		tableMembers.setEvents(self.members, 'tableMembersUsers');
	},

	selectDirectLine(i) {
		let self = GruposEditarController;

		let bot = self.bots[i].directLine;
		let botName = self.bots[i].botName;
		$('#directLineSecret').val(bot);
		$('#botId').val(botName);
	},

	sendGroup() {
		let self = this;

		let participants = [];
		for(let i = 0; i < self.members.length; i++) {
			participants.push(self.members[i].id);
		}

		let participantsOld = [];
		for(let i = 0; i < self.membersOld.length; i++) {
			participantsOld.push(self.membersOld[i].id);
		}

		// Comprobar checkboxs
		if($('#saludoInicial').prop('checked')) {
			$('#saludoInicial').val(1);
		} else {
			$('#saludoInicial').val(0);
		}
		if($('#enabled').prop('checked')) {
			$('#enabled').val(1);
		} else {
			$('#enabled').val(0);
		}

		self.group = {
			idAdmin: $('#SYSNotifUser').text(),
			nameAdmin: $('#SYSNotifUserName').val(),
			groupName: $('#groupName').val(),
			participants: participants,
			participantsOld: participantsOld,
			country: $('#pais').val()
		};

		self.botConfig = {
			idUserOrGroup: self.groupData.groupName,
			directLineSecret: $('#directLineSecret').val(),
			botId: $('#botId').val(),
			isGroup: 1,
			enabled: $('#enabled').val(),
			botUser: $('#botUser').val(),
			numVecesNoMatch: $('#numVecesNoMatch').val(),
			textoNoMatch: $('#textoNoMatch').val(),
			userNotificarNoMatch: $('#userNotificarNoMatch').val(),
			messageNotifNoMatch: $('#textoNotificarNoMatch').val(),
			SaludoInicial: $('#saludoInicial').val()
		};

		let parameters = {
			group: JSON.stringify(self.group),
			botConfig: JSON.stringify(self.botConfig),
			isEditName: self.isEditName,
			isEditAdmin: self.isEditAdmin,
			isEditBot: self.isEditBot,
			groupId: self.groupData.idGroup,
			nameChange: pf.const.language.RSC1276,
			greeting: pf.const.language.RSC1277
		};
		ajaxComunCallWithCallback('editGroup', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let successTitle = pf.const.language.RSC78;
				let successContent = pf.const.language.RSC106;
				pf.utils.showInfoDialog(successTitle, successContent);
				window.location.href = '#!grupos';
			}
		});
	},

	clickEvents(data, type = null) {
		let self = GruposEditarController;

		if(type) {
			self.userType = type;
		}
		self.userClick = data;
		switch(self.userType) {
			case 'adminGroup':
				$('#SYSNotifUser').text(self.userClick.id);
				let surname1 = '';
				if(self.userClick.userApellidos && self.userClick.userApellidos != 'null') {
					surname1 = self.userClick.userApellidos;
				}

				let surname2 = '';
				if(self.userClick.userApellidos2 && self.userClick.userApellidos2 != 'null') {
					surname2 = self.userClick.userApellidos2;
				}

				$('#SYSNotifUserName').val(self.userClick.nameUser + ' ' + self.userClick.userApellidos + ' ' + self.userClick.userApellidos2);

				self.isEditAdmin = 1;
				break;
			case 'userBot':
				$('#botUser').val(self.userClick.id);
				$('#botUserName').text(self.userClick.nameUser);
				self.isEditBot = 1;
				break;
			case 'userNotif':
				$('#userNotificarNoMatch').val(self.userClick.id);
				$('#userNotificarNoMatchName').text(self.userClick.nameUser);
				self.isEditBot = 1;
				break;
			case 'bots':
				$('#directLineSecret').val(self.userClick.directLine);
				$('#botId').val(self.userClick.botName);
				self.isEditBot = 1;
				break;
			case 'addMembers':
				self.members = data;
				tableMembers.setEvents(self.members, 'tableMembersUsers', 'editGroups');
				break;
			case 'removeMember':
				self.members.splice(data, 1);
				self.crewObject.members = self.members;
				tableMembers.setEvents(self.members, 'tableMembersUsers', 'editGroups');
				break;
			// Seleccionar país
			case 'country':
				$('#pais').val(data.isocode);
				self.countryFilter = data.isocode;
				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').show();
				break;
		}
	}
}