let ProyectosVideocallController = {
	url: null,
	idProject: '',
	idProjectTimestamp: '',
	projectName: '',
	participants: '',
	videocallJID: '',
	participantsTable: false,
	participantsTableIn: false,
	participantsNotInCall: [],
	participantsInCall: [],
	URLVideoCalls: '',
	timer: null,
	gdpr: '',
	videocallNoParticipants: '0',
	stampMision: '',
	dataTableParticipants: null,
	dataTableInCall: null,

	resetData() {
		let self = this;

		self.url = null;
		self.idProject = sessionStorage.getItem('idProject');
		self.idProjectTimestamp = atob(sessionStorage.getItem('idProjectTimestamp')).replace(/(<([^>]+)>)/ig, '');
		self.projectName = atob(sessionStorage.getItem('projectName')).replace(/(<([^>]+)>)/ig, '');
		self.participants = '';
		self.videocallJID = atob(sessionStorage.getItem('videocallJID'));
		self.participantsTable = false;
		self.participantsTableIn = false;
		self.participantsNotInCall = [];
		self.participantsInCall = [];
		self.URLVideoCalls = '';
		self.gdpr = sessionStorage['STCMBackEnd:GDPR'];
		self.videocallNoParticipants = sessionStorage['videocallNoParticipants'];
		self.stampMision = atob(sessionStorage.getItem('stamMissionVideocall'));
		self.dataTableParticipants = null;
		self.dataTableInCall = null;
	},

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

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

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

		// Opciones de header
		let jsonsubopt = {
			manageUsers: 'gestionUsers'
		};

		let nav = `
			${createSubOptionVideocallManageUsers(jsonsubopt.manageUsers)}
		`;

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

		$('#gestionUsers svg').css('width', '16px');
		$('#gestionUsers svg').css('height', '16px');

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

		// Volver a Proyectos
		$('#back').off().on('click', function() {
			self.moderatorLeaveCall();
			window.location.href = '#!proyectos_edit';
		});

		self.loadLang();

		self.requestConfig();

		// Gestión de usuarios
		$('#gestionUsers').off().on('click', function() {
			self.usersInCall();
		});

		// Candidatos
		$('#candidatos').off().on('click', function() {
			$('#candidatos').addClass('active');
			$('#candidatosBody').removeClass('d-none');
			$('#candidatosFooter').removeClass('d-none');
			$('#participantes').removeClass('active');
			$('#participantesBody').addClass('d-none');
			$('#participantesFooter').addClass('d-none');

			// Ajustar columnas de tabla
			self.dataTableParticipants.columns.adjust();
		});

		// Participantes
		$('#participantes').off().on('click', function() {
			$('#participantes').addClass('active');
			$('#participantesBody').removeClass('d-none');
			$('#participantesFooter').removeClass('d-none');
			$('#candidatos').removeClass('active');
			$('#candidatosBody').addClass('d-none');
			$('#candidatosFooter').addClass('d-none');

			// Ajustar columnas de tabla
			self.dataTableInCall.columns.adjust();
		});
	},

	requestConfig() {
		let self = this;

		ajaxComunCallWithCallback('getCMBPConfig', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				let config = ajaxReturn.result[0];
				self.URLVideoCalls = config.URLVideoCalls;
				if(self.URLVideoCalls == '' || self.URLVideoCalls == undefined || self.URLVideoCalls == null) {
					let warningTitle = pf.const.language.RSC61;
					let warningContent = pf.const.language.RSC993;
					pf.utils.showInfoDialog(warningTitle, warningContent);
					return;
				}
				self.printIframe();
			}
		});
	},

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

		// TITLES
		$('#sendReminder').attr('title', pf.const.language.RSC2500);
		$('#removeParticipantsService').attr('title', pf.const.language.RSC1464);
	},

	printIframe() {
		let self = this;

		self.url = self.URLVideoCalls + self.idProject + self.stampMision;

		//calc(100vh - 231px)
		let counter = 0;
		let iframe = `
			<div class="">
				<iframe id="videocallCont" src="${self.url}" class="w-100 he-cal-100vh-n232" allowfullscreen allow="microphone;camera;display-capture"></iframe>
			</div>
		`;
		$('#iframeVideocall').html(iframe);

		$('#videocallCont').on('load', function() {
			counter++;
			if(counter > 1) {
				self.moderatorLeaveCall();
			} else {
				self.getCMBPProjectsParticipantes();
			}
		});
	},

	// Petición de participantes del proyecto
	getCMBPProjectsParticipantes() {
		let self = this;

		let parameters = {
			id: self.idProject
		};
		ajaxComunCallWithCallback('getCMBPProjectsParticipantes', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.participants = ajaxReturn.result;
				if(self.videocallNoParticipants == '1') {
					let noParticiants = [];
					self.sendIncomingCall('start', noParticiants);
				} else {
					self.sendIncomingCall('start', self.participants);
				}

				self.registerCall();
			}
		});
	},

	renderProjectParticipants() {
		let self = this;

		if(self.participantsTable == false) {
			self.participantsTable = true;
		} else {
			$('#tableParticipants').dataTable().fnDestroy();
		}

		let nameSurnameHead = `<th scope="col" title="${pf.const.language.RSC123}">${pf.const.language.RSC123}</th>`;
		let nameSurnameFilter = `<td>name</td>`;

		// Control GDPR
		if(self.gdpr == '1') {
			nameSurnameHead = '';
			nameSurnameFilter = '';
		}

		let table = `
			<thead>
				<tr>
					${nameSurnameHead}
					<th scope="col" title="${pf.const.language.RSC136}">${pf.const.language.RSC136}</th>
					<th scope="col" title="${pf.const.language.RSC366}">${pf.const.language.RSC366}</th>
					<th scope="col" title="${pf.const.language.RSC456}">${pf.const.language.RSC456}</th>
				</tr>
			</thead>

			<thead class="filtersResult">
				<tr>
					${nameSurnameFilter}
					<td>mail</td>
					<td>id</td>
					<td>since</td>
				</tr>
			</thead>

			<tbody>
		`;

		let size = self.participantsNotInCall.length;
		for(let i = 0; i < size; i++) {
			let nameSurnameBody = `
				<td class="text-truncate" title="${self.participantsNotInCall[i].user}">
					<input type="checkbox" class="selection" data-idUser="${self.participantsNotInCall[i].idUser}">
					${self.participantsNotInCall[i].user}
				</td>
			`;

			let emailBody = `<td class="text-truncate" title="${self.participantsNotInCall[i].email}">${self.participantsNotInCall[i].email}</td>`;

			// Control GDPR
			if(self.gdpr == '1') {
				nameSurnameBody = '';
				emailBody = `
					<td class="text-truncate" title="${self.participantsNotInCall[i].email}">
						<input type="checkbox" class="selection" data-idUser="${self.participantsNotInCall[i].idUser}">
						${self.participantsNotInCall[i].email}
					</td>
				`;
			}

			table += `
				<tr id="${self.participantsNotInCall[i].idUser}">
					${nameSurnameBody}
					${emailBody}
					<td class="text-truncate" title="${self.participantsNotInCall[i].idUser}">${self.participantsNotInCall[i].idUser}</td>
					<td class="text-truncate" title="${self.participantsNotInCall[i].miembrodesde}">${self.participantsNotInCall[i].miembrodesde}</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

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

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

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

		self.dataTableParticipants = $('#tableParticipants').DataTable({
			scrollY: 300,
			scroller: false,
			paging: true,
			pageLength: 25,
			retrieve: true,
			language: pf.const.language_table,
			autoWidth: false,
			aaSorting: []
		});

		setTimeout(function() {
			self.dataTableParticipants.columns.adjust();
		}, 200);

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

		// Apply the search
		applyTheSearch(self.dataTableParticipants, 'filtersResult');

		self.tableParticipantsEvents();
	},

	tableParticipantsEvents() {
		let self = this;

		// Enviar recordatorio
		$('#sendReminder').off().on('click', function() {
			let participants = [];
			$('#tableParticipants tr').each(function() {
				let cheked = $(this).find('.selection');
				if(cheked.prop('checked')) {
					let idUser = $(this).attr('id');
					participants.push(idUser);
				}
			});
			$('#surveyClose').trigger('click');

			self.sendIncomingCall('re', participants);
		});
	},

	renderProjectParticipantsIn() {
		let self = this;

		if(self.participantsTableIn == false) {
			self.participantsTableIn = true;
		} else {
			$('#tableParticipantsInCall').html('');
			$('#tableParticipantsInCall').dataTable().fnDestroy();
		}

		let nameSurnameHead = `<th scope="col" title="${pf.const.language.RSC123}">${pf.const.language.RSC123}</th>`;
		let nameSurnameFilter = `<td>name</td>`;

		// Control GDPR
		if(self.gdpr == '1') {
			nameSurnameHead = '';
			nameSurnameFilter = '';
		}

		let table = `
			<thead>
				<tr>
					${nameSurnameHead}
					<th scope="col" title="${pf.const.language.RSC136}">${pf.const.language.RSC136}</th>
					<th scope="col" title="${pf.const.language.RSC366}">${pf.const.language.RSC366}</th>
					<th scope="col" title="${pf.const.language.RSC456}">${pf.const.language.RSC456}</th>
				</tr>
			</thead>

			<thead class="filtersResult">
				<tr>
					${nameSurnameFilter}
					<td>mail</td>
					<td>id</td>
					<td>since</td>
				</tr>
			</thead>

			<tbody>
		`;

		let size = self.participantsInCall.length;
		for(let i = 0; i < size; i++) {
			let nameSurnameBody = `
				<td class="text-truncate" title="${self.participantsInCall[i].user}">
					<input type="checkbox" class="selection" data-idUser="${self.participantsInCall[i].idUser}">
					${self.participantsInCall[i].user}
				</td>
			`;

			let emailBody = `<td class="text-truncate" title="${self.participantsInCall[i].email}">${self.participantsInCall[i].email}</td>`;

			// Control GDPR
			if(self.gdpr == '1') {
				nameSurnameBody = '';
				emailBody = `
					<td class="text-truncate" title="${self.participantsInCall[i].email}">
						<input type="checkbox" class="selection" data-idUser="${self.participantsInCall[i].idUser}">
						${self.participantsInCall[i].email}
					</td>
				`;
			}

			table += `
				<tr id="${self.participantsInCall[i].idUser}">
					${nameSurnameBody}
					${emailBody}
					<td class="text-truncate" title="${self.participantsInCall[i].idUser}">${self.participantsInCall[i].idUser}</td>
					<td class="text-truncate" title="${self.participantsInCall[i].miembrodesde}">${self.participantsInCall[i].miembrodesde}</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

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

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

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

		self.dataTableInCall = $('#tableParticipantsInCall').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			scrollY: 300,
			scroller: false,
			paging: true,
			pageLength: 25,
			autoWidth: false,
			aaSorting: []
		});

		setTimeout(function() {
			self.dataTableInCall.columns.adjust();
		}, 200);

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

		// Apply the search
		applyTheSearch(self.dataTableInCall, 'filtersResult');

		self.tableParticipantsInEvents();
	},

	tableParticipantsInEvents() {
		let self = this;

		$('#removeParticipantsService').off().on('click', function() {
			let participants = [];
			$('#tableParticipantsInCall tr').each(function() {
				let cheked = $(this).find('.selection');
				if(cheked.prop('checked')) {
					let idUser = $(this).attr('id');
					participants.push(idUser);
				}
			});
			$('#surveyClose').trigger('click');
			self.moderatorOutUserCall(participants);
		});
	},

	resetTimer() {
		let self = this;

		clearInterval(self.timer);
		self.timer = null;
	},

	sendIncomingCall(moment, participants) {
		let self = this;

		if(moment == 're') {
			// La videollamada ya ha iniciado, recuerda unirte para completar la misión. Gracias.
			let mensaje = pf.const.language.RSC2501;

			let emailsToSend = [];
			for(let i = 0; i < participants.length; i++) {
				let obj = {
					id: participants[i]
				};

				emailsToSend.push(obj);
			}

			let parameters = {
				from: self.videocallJID,
				emailsToSend: JSON.stringify(emailsToSend),
				message: mensaje,
				idlist: ''
			};
			ajaxComunCallWithCallback('postMessageMultiple', parameters, function(ajaxReturn) {
				if(ajaxReturn) {
					//
				}
			});
		}
	},

	usersInCall() {
		let self = this;

		let parameters = {
			idcall: 'CODE#' + self.idProject + self.stampMision
		};
		ajaxComunCallWithCallback('usersInCall', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let participantsIn = [];
				if(ajaxReturn.result.length > 0) {
					participantsIn = ajaxReturn.result;
				}

				let participantsInCall = [];
				let sizeIn = participantsIn.length;
				for(let i = 0; i < sizeIn; i++) {
					participantsInCall.push(participantsIn[i].jid);
				}

				self.participantsInCall = [];
				self.participantsNotInCall = [];
				let sizeOut = self.participants.length;
				for(let i = 0; i < sizeOut; i++) {
					if(!participantsInCall.includes(self.participants[i].idUser)) {
						self.participantsNotInCall.push(self.participants[i]);
					} else {
						self.participantsInCall.push(self.participants[i]);
					}
				}

				self.renderProjectParticipants();
				self.renderProjectParticipantsIn();
			}
		});
	},

	moderatorLeaveCall() {
		let self = this;

		self.resetTimer();

		let parameters = {
			jid: self.videocallJID,
			type: 'video',
			idcall: 'CODE#' + self.idProject + self.stampMision
		};
		ajaxComunCallWithCallback('moderatorLeaveCall', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				window.location.href = '#!proyectos_edit';
			}
		});
	},

	registerCall() {
		let self = this;

		let now = new Date();
		let timeStamp = now.getTime();

		let parameters = {
			jid: self.videocallJID,
			bid: self.idProject,
			type: 'video',
			idcall: 'CODE#' + self.idProject + self.stampMision,
			stamp: timeStamp
		};
		ajaxComunCallWithCallback('registerCall', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				// Register Call
			}
		});
	},

	moderatorOutUserCall(participants) {
		let self = this;

		let parameters = {
			jid: participants,
			idcall: 'CODE#' + self.idProject + self.stampMision
		};
		ajaxComunCallWithCallback('moderatorOutUserCall', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				//
			}
		});
	}
};