stcmbackend.communymanagement = {
	chatList: [],
	usersList: [],
	currentChat: '',
	currentUser: '',
	appChats: {},
	appGroups: {},
	appMessages: {},
	appUsers: {},

	registerFirebaseToken(token) {
		CommunityManagement.firebaseToken = token;
	},

	onReceivedMessageFirebase(payload, backgroundMode) {
		// Datos
		let mission = '';
		if(payload.data.mision) {
			mission = JSON.parse(payload.data.mision);
		}

		let info = null;
		if (payload && payload.data && payload.data.info) {
    		info = JSON.parse(payload.data.info.replace(/\n/g, '\\n'));
		}

		if(payload.notification != undefined) {
			let message = payload.notification.body;
			let contactElement = '';
			if(!backgroundMode) {
				// Subir arriba el chat
				contactElement = $('.contact-list [data-bid="' + info.jid + '"]');
				if(contactElement.length == 0) {
					// Recargar lista de chats
					CommunityManagement.chatsEmailArray = [CommunityManagement.jsonUser.token];
					CommunityManagement.contactPage = 0;
					stcmbackend.communymanagement.chatList = [];
					stcmbackend.communymanagement.GroupsList = [];
					CommunityManagement.renderChatlist();
				} else {
					let displayText = payload.data.isChatBot ? payload.data.messageText : message;
					contactElement.find('.contact-preview').find('.contact-text').find('.font-preview').text(displayText);
					var dropdownMenuContent = contactElement.find('.dropdown-menu').html();
					$('.contact-list [data-bid="' + info.jid + '"]').remove();
					$('.contact-list').prepend(contactElement);
					contactElement.find('.dropdown-menu').html(dropdownMenuContent);
					$('.contact-list').find('.contact-time .classChatTime').data('stamp')
					var $contactDiv = $('.contact-list .contact');

					// Obtiene el valor del atributo data-bid dentro del div
					var dataBidInsideDiv = $contactDiv.data('bid');

					// Selecciona el <a> que está fuera del div y tiene el mismo data-bid
					var $aOutsideDiv = $(`a.deleteChat[data-bid="${dataBidInsideDiv}"]`).not('.contact .deleteChat');

					// Elimina el <a> seleccionado
					if ($aOutsideDiv.length) {
						$aOutsideDiv.remove();
					}
					CommunityManagement.events.addClickToChat();
					

					// Fecha
					let now = new Date();
					let stamp = now.getTime();
					let hours = now.getHours();
					if(parseInt(hours) < 10) {
						hours = '0' + hours;
					}
					let minutes = now.getMinutes();
					if(parseInt(minutes) < 10) {
						minutes = '0' + minutes;
					}
					contactElement.find('.contact-time').find('.classChatTime').data('stamp', stamp);
					contactElement.find('.contact-time').find('.classChatTime').text(hours + ':' + minutes);
					if(stcmbackend.communymanagement.currentChat.type == undefined || info.jid != CommunityManagement.currentChat  ) {
						contactElement.find('.contact-time').find('.classChatTime').addClass('new-message-color');
						let count = contactElement.find('.contact-time').find('.new-message').find('p').text();
						contactElement.find('.contact-time').find('.new-message').find('p').text(parseInt(count) + 1);
						contactElement.find('.contact-time').find('.new-message').removeClass('d-none');
					}else {
						let service = '';
						let parameters = {};
						// Hacer opciones si esta activo el chat
						if(stcmbackend.communymanagement.currentChat.type == 'chat' ) {
							
							// Recepción de mensajes pendientes de contacto
							service = 'getPendingMessages_SaaS';
							parameters = {
								userA: CommunityManagement.jsonUser.token,
								userB: stcmbackend.communymanagement.currentChat.email,
								stamp: CommunityManagement.lastStampServer
							};
							
							// Mostrar el spinner para ChatBot
							if(CommunityManagement.isVoiceAssistant){
								$('#chatBotSpinner').removeClass('d-none');
								$('#chatBotSpinner').addClass('d-flex');
							}
					
						} else if(stcmbackend.communymanagement.currentChat.type == 'groupchat') {
							// Recepción de mensajes pendientes de grupo
							service = 'getPendingMessagesGroup_SaaS';
							parameters = {
								userA: CommunityManagement.jsonUser.token,
								groupID: stcmbackend.communymanagement.currentChat.idgroup,
								stamp: CommunityManagement.lastStampServer
							};
						}
					
						// Petición ajax
						ajaxComunCallWithCallback(service, parameters, function(ajaxReturn) {
							if(ajaxReturn) {
								let size = ajaxReturn.result.length;
								let msg = payload.data.messageText;
								// Ocultar el spinner después de que el mensaje haya sido enviado
								if(CommunityManagement.isVoiceAssistant){
									$('#chatBotSpinner').removeClass('d-flex');
									$('#chatBotSpinner').addClass('d-none');
								}
							
								if(!size && CommunityManagement.isVoiceAssistant ){
									let templatechat = '';
									let result =  {
										msg:msg,
										stampServer: CommunityManagement.lastStampServer,
										stamp: stamp,
										direction: "in"
									}
								
									templatechat = CommunityManagement.printMessage(result);
									$('.chat').append(templatechat);
									$('.chat').scrollTop($('.chat').prop('scrollHeight'));
									CommunityManagement.messageEvents();
								}
								for(let i = 0; i < size; i++) {
									let templatechat = CommunityManagement.printMessage(ajaxReturn.result[i]);
									$('.chat').append(templatechat);
									$('.chat').scrollTop($('.chat').prop('scrollHeight'));
									CommunityManagement.messageEvents();

									// Control de mensajes no vistos
									if(stcmbackend.communymanagement.currentChat.type == 'chat' ) {
										// Marcar como leidos mensajes de contacto
										let parameters = {
											userA: CommunityManagement.jsonUser.token,
											userB: stcmbackend.communymanagement.currentChat.email
										};
										ajaxComunCallWithCallback('markAsReaded_SaaS', parameters, function(ajaxReturn) {
											if(ajaxReturn) {
												//
											}
										}, false);
									} else if(stcmbackend.communymanagement.currentChat.type == 'groupchat') {
										// Marcar como leidos mensajes de grupo
										let parameters = {
											userA: CommunityManagement.jsonUser.token,
											groupID: stcmbackend.communymanagement.currentChat.idgroup
										};
										ajaxComunCallWithCallback('markAsReadedGroup_SaaS', parameters, function(ajaxReturn) {
											if(ajaxReturn) {
												//
											}
										}, false);
									}
								}
							}
						}, false);
					}
				}
			}
		}
	}
};

var UsersList = function(app) {
	function User(obj) {
		obj.nick = obj.name;
		obj.name = obj.userNombre;
		obj.bid = obj.jidUser;
		obj.email = obj.token;
		obj.mute = {muted: '0'};
		obj.blocked = '0';
		stcmbackend.communymanagement.usersList.push(obj);
	}

	stcmbackend.communymanagement.appUsers = User;
	return stcmbackend.communymanagement.appUsers;
}(ChatList || {});

var ChatList = function(app) {
	function Chat(obj) {
		stcmbackend.communymanagement.chatList.push(obj);
	}

	Chat.prototype.addMessage = function(msg) {
		this.messages.push(msg);
	};

	Chat.prototype.addGroup = function(group) {
		this.groups.push(group);
	};

	stcmbackend.communymanagement.appChats = Chat;
	return stcmbackend.communymanagement.appChats;
}(ChatList || {});

var GroupsList = function(app) {
	function Group(obj) {
		stcmbackend.communymanagement.chatList.push(obj);
	}

	Group.prototype.addMember = function(contact) {
		this.members.push(contact);
	};

	Group.prototype.addMessage = function(msg) {
		this.messages.push(msg);
	};

	stcmbackend.communymanagement.appGroups = Group;
	return stcmbackend.communymanagement.appGroups;
}(GroupsList || {});

var Messages = function(app) {
	function Message(text, name, time, direction, group) {
		this.text = text;
		this.name = name;
		this.time = time;
		this.direction = direction;
		this.group = group;
	}

	stcmbackend.communymanagement.appMessages = Message;
	return stcmbackend.communymanagement.appMessages;
}(Messages || {});