class ReportGeneratorController {
	constructor(reports, parameters) {
		this.ajax = false;
		this.continueReport = true;
		this.reports = reports;
		this.parameters = parameters;
		this.idReport = '';
		this.errorsReports = {
			images: false,
			excel: false,
			wc: false,
			ppt: false,
			word: false
		};
	}

	executeReports() {
		let self = this;

		self.idReport = Math.floor(Date.now() / 1000);

		$('#show-generating-reports').css('visibility', 'visible');
		let report = {
			name: self.parameters.nameMission,
			id: self.idReport,
			title: pf.const.language.RSC1941,
			subtitle: pf.const.language.RSC49,
			cancelButton: true
		}
		CardGeneratorController.addNotification(report);

		$(`#cancelDowload${self.idReport}`).off().on('click', (e)=>{
			e.preventDefault();
			self.cancelAjax();
		});

		if(self.reports.images) {
			self.getImagesSurvey();
		} else if(self.reports.excel) {
			self.generateExcel();
		} else if(self.reports.wc) {
			self.generateWordcloudExcel();
		} else if(self.reports.ppt) {
			self.generatePermanentReportData('powerpoint');
		} else if(self.reports.word) {
			self.generatePermanentReportData('word');
		}
	}

	// Recopilación de multimedia
	getImagesSurvey() {
		let self = this;

		$(`#downloadCardTitle_${self.idReport}`).html(pf.const.language.RSC547 + ' ' + pf.const.language.RSC544 + ' - ' + self.parameters.nameMission);
		let steps = pf.const.language.RSC534 + '<br>' + pf.const.language.RSC535 + '...';
		$(`#downloadCardText_${self.idReport}`).html(steps);

		let parameters = {
			user: self.parameters.user,
			survey: self.parameters.survey,
			idmision: self.parameters.idmision,
			stampMision: self.parameters.stampMision,
			project: self.parameters.project,
			numPregPerf: self.parameters.numPregPerf,
			isContinuing: self.parameters.isContinuing
		}
		ajaxComunCallWithCallback('getMultimediaReport', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				if(ajaxReturn.result != 'Images generated') {
					self.errorsReports.images = true;
				}

				// Borrado de carpeta auxiliar de multimedia
				let parameters = {
					user: self.parameters.user
				}
				ajaxComunCallWithCallback('deleteFilesUser', parameters, function(ajaxReturn) {
					if(ajaxReturn) {
						//
					}
				}, false);

				// Control para la cancelación de reporte
				if(!self.continueReport) {
					return false;
				}

				if(self.reports.excel) {
					self.generateExcel();
				} else if(self.reports.wc) {
					self.generateWordcloudExcel();
				} else if(self.reports.ppt) {
					self.generatePermanentReportData('powerpoint');
				} else if(self.reports.word) {
					self.generatePermanentReportData('word');
				} else {
					self.finishReports();
				}
			}
		}, false);
	}

	// Generar excel
	generateExcel() {
		let self = this;

		$(`#downloadCardTitle_${self.idReport}`).html(pf.const.language.RSC547 + ' ' + pf.const.language.RSC540 + ' - ' + self.parameters.nameMission);
		let steps = pf.const.language.RSC534 + '<br>' + pf.const.language.RSC533 + '...';
		$(`#downloadCardText_${self.idReport}`).html(steps);

		let parameters = {
			user: self.parameters.user,
			survey: self.parameters.survey,
			idmision: self.parameters.idmision,
			nameMission: self.parameters.nameMission,
			stampMision: self.parameters.stampMision,
			project: self.parameters.project,
			numPregPerf: self.parameters.numPregPerf,
			timestamp: self.parameters.timestamp,
			excelDataOpt: self.parameters.excelDataOpt,
			headersExcel: self.parameters.headersExcel,
			questionIdOut: self.parameters.questionIdOut,
			consumo: self.parameters.consumo,
			isContinuing: self.parameters.isContinuing,
			startDate: self.parameters.startDate,
			endDate: self.parameters.endDate
		}
		ajaxComunCallWithCallback('generateExcelReport', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				// Control para la cancelación de reporte
				if(!self.continueReport) {
					return false;
				}

				if(self.reports.wc) {
					self.generateWordcloudExcel();
				} else if(self.reports.ppt) {
					self.generatePermanentReportData('powerpoint');
				} else if(self.reports.word) {
					self.generatePermanentReportData('word');
				} else {
					self.finishReports();
				}
			}
		}, false);
	}

	// Generar excel de wordcloud
	generateWordcloudExcel() {
		let self = this;

		let parameters = {
			user: self.parameters.user,
			survey: self.parameters.survey,
			idmision: self.parameters.idmision,
			stampMision: self.parameters.stampMision,
			project: self.parameters.project,
			numPregPerf: self.parameters.numPregPerf
		}
		ajaxComunCallWithCallback('generateWordcloudExcel', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				// Borrado de carpeta auxiliar de excel
				let parameters = {
					user: self.parameters.user
				}
				ajaxComunCallWithCallback('deleteFilesUser', parameters, function(ajaxReturn) {
					if(ajaxReturn) {
						//
					}
				}, false);

				// Control para la cancelación de reporte
				if(!self.continueReport) {
					return false;
				}

				if(self.reports.ppt) {
					self.generatePermanentReportData('powerpoint');
				} else if(self.reports.word) {
					self.generatePermanentReportData('word');
				} else {
					self.finishReports();
				}
			}
		}, false);
	}

	// Generar datos de reporte
	generatePermanentReportData(element) {
		let self = this;

		// RSC50: Paso 1 de 3
		// RSC58: Procesando datos...
		$(`#downloadCardTitle_${self.idReport}`).html(pf.const.language.RSC547 + ' ' + element + ' - ' + self.parameters.nameMission);
		let steps = pf.const.language.RSC50 + '<br>' + pf.const.language.RSC58;
		$(`#downloadCardText_${self.idReport}`).html(steps);

		let parameters = {
			idSurvey: self.parameters.survey,
			numPreguntasPerfilacionEnAnalyticMostreo: self.parameters.numPregPerf,
			idmision: self.parameters.idmision,
			project: self.parameters.project
		};
		ajaxComunCallWithCallback('getCountryAndParticipation', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				// Control para la cancelación de reporte
				if(!self.continueReport) {
					return false;
				}

				// Recoge los datos de cada usuario que ha respondido la encuesta, recoge la participación por estado de cada país y lo recopila todo en un mapa.
				let data = ajaxReturn.countryAndParticipation;

				let mapaPaisesRegiones = new Map();

				for(let i = 0; i < data.length; i++) {
					let pais = data[i][0];
					let estado = data[i][1];

					if(!mapaPaisesRegiones.has(pais)) {
						mapaPaisesRegiones.set(pais, new Map());
					}

					let objPais = {
						s1: pais,
						s2: {
							s3: estado,
							s4: 0
						}
					}

					objPais.s2.s4++;
					let a = mapaPaisesRegiones.get(objPais.s1).has(objPais.s2.s3);
					if(a) {
						mapaPaisesRegiones.get(objPais.s1).set(objPais.s2.s3 , mapaPaisesRegiones.get(objPais.s1).get(objPais.s2.s3) + 1);
					} else {
						mapaPaisesRegiones.get(objPais.s1).set(objPais.s2.s3,1);
					}
				}

				$('#result_graph_ppt_aux').html('');

				// Por cada país crea un canvas dentro de '#result_graph_ppt_aux' y crea el HeatMap
				for(let [key, value] of mapaPaisesRegiones) {
					let arrayLabels = [];
					let arrayLabelsData = [];
					for(let [key2, value2] of value) {
						arrayLabels.push(key2);
						arrayLabelsData.push(value2);
					}
					// Pasar a porcentajes los datos
					let total = 0;
					for(let i = 0; i < arrayLabelsData.length; i++) {
						total += arrayLabelsData[i];
					}
					for(let i = 0; i < arrayLabelsData.length; i++) {
						// '* 10) / 10' 1 decimal, '* 100) / 100' 2 decimales, etc.
						arrayLabelsData[i] = Math.round((((100 * arrayLabelsData[i]) / total)) * 1) / 1;
					}

					let idPpt = 'result_graph_ppt_' + key;
					$('#result_graph_ppt_aux').append(
						`<canvas id="${idPpt}" class="bg-white d-none" width="1280" height="700"></canvas>`
					);
					let ctx = document.getElementById(idPpt).getContext('2d');

					// Array de colores para representar el mapa (10 opciones)
					let quantity = 10;
					let colors = generateColors(self.parameters.primaryColor, self.parameters.secundaryColor, quantity);

					let heatMap = new HeatMap(key, 0, '', arrayLabels, arrayLabelsData, ctx, true, colors);

					heatMap.createHeatMap();
				}

				ajaxComunCallWithCallback('generatePermanentReportData', self.parameters, function(ajaxReturn) {
					if(ajaxReturn) {
						// Control para la cancelación de reporte
						if(!self.continueReport) {
							return false;
						}

						// Control de encuesta sin usuarios
						if(ajaxReturn.result == 'No users') {
							$(`#downloadCardTitle_${self.idReport}`).html(pf.const.language.RSC1517 + ' - ' + self.parameters.idmision);
							$(`#downloadCardTitle_${self.idReport}`).addClass('main-color-text');
							$(`#downloadCardText_${self.idReport}`).html(pf.const.language.RSC1518);
							$(`#${self.idReport}`).removeClass('runningReport');
							CardGeneratorController.updateIcon();
							CardGeneratorController.showOnScreenNotification(self.idReport, pf.const.language.RSC55, 'check-circle');
						} else {
							self.generateReportInitialGraphs(ajaxReturn, element);
						}
					}
				}, false);
			}
		}, false);
	}

	// Generar gráficas iniciales
	generateReportInitialGraphs(dataAnalytics, element) {
		let self = this;

		let heatMaps = [];

		dataAnalytics['numPregPerf'] = self.parameters.numPregPerf;

		/* Recoge los canvas creados en muestreo y los añades a las charts generales */
		$('#result_graph_ppt_aux canvas').each(function() {
			let ctx = $(this).attr('id');
			let url_base64jp = document.getElementById(ctx).toDataURL('image/jpg');
			heatMaps.push(url_base64jp);
		});

		$('#result_graph_ppt_aux canvas').html('');

		dataAnalytics['heatMaps'] = heatMaps;
		self.generateWordclouds(dataAnalytics, element);
	}

	// Generar wordclouds
	generateWordclouds(dataAnalytics, element) {
		let self = this;

		// RSC51: Paso 2 de 3
		// RSC52: Generando gráficas...
		let steps = pf.const.language.RSC51 + '<br>' + pf.const.language.RSC52;
		$(`#downloadCardText_${self.idReport}`).html(steps);

		let wordcloudImgArray = [];

		let i = 0;
		let indexP = 0;
		let arrayP = [];

		function createWordcloud(question, i) {
			/*if(question.wordCloud[i] == 'no' || (question.typeQuestion[i] == '|' && question.ocr[i] == '0') || (question.typeQuestion[i] == '7' && question.ocr[i] == '0') || (question.typeQuestion[i] == 'J' && question.ocr[i] == '0')) {*/
				// Reinicio para las preguntas tipo 'P'
				indexP = 0;
				arrayP = [];

				let obj = {
					wordCloud: '0'
				};

				wordcloudImgArray.push(obj);

				i++;

				if(i < question.wordCloud.length) {
					// Control para la cancelación de reporte
					if(self.continueReport) {
						createWordcloud(dataAnalytics, i);
					} else {
						return false;
					}
				} else {
					dataAnalytics.wordcloudImgArray = wordcloudImgArray;

					if(element == 'powerpoint') {
						self.generatePermanentPowerpointWithWordcloud(dataAnalytics);
					} else if(element == 'word') {
						self.generatePermanentWordWithWordcloud(dataAnalytics);
					}
				}
			/*} else if(Array.isArray(question.wordCloud[i])) {
				// Especial para las tipo 'P' Palabras (1) o frases (2)
				let wordsOrPhrases = 1;

				if(indexP < question.wordCloud[i].length) {
					// Ruta WordCloud
					let src = self.parameters.wordCloudURL + '/?a=' + self.parameters.survey + '&b=' + question.wordCloud[i][indexP] + '&c=&d=&e=&f=&g=' + self.parameters.primaryColor + '&h=' + self.parameters.secundaryColor + '&i=' + wordsOrPhrases + '&j=' + self.parameters.numberWordsWordcloud + '&k=&l=&m=&n=&o=';

					window.addEventListener('message', loadWordCloud);
					function loadWordCloud(event) {
						arrayP.push(event.data);

						window.removeEventListener('message', loadWordCloud);

						indexP++;
						setTimeout(function() {
							if(self.continueReport) {
								// Control para la cancelación de reporte
								if(self.continueReport) {
									createWordcloud(dataAnalytics, i);
								} else {
									return false;
								}
							} else {
								return false;
							}
						}, 500);
					}
					$('#result_word_cloud').attr('src', src);
				} else {
					let wordcloud = '3';

					let obj = {
						wordCloud: wordcloud,
						element: arrayP
					};

					wordcloudImgArray.push(obj);

					i++;
					if(i < question.wordCloud.length) {
						// Reinicio para las preguntas tipo 'P'
						indexP = 0;
						arrayP = [];
						// Control para la cancelación de reporte
						if(self.continueReport) {
							createWordcloud(dataAnalytics, i);
						} else {
							return false;
						}
					} else {
						dataAnalytics.wordcloudImgArray = wordcloudImgArray;

						if(element == 'powerpoint') {
							self.generatePermanentPowerpointWithWordcloud(dataAnalytics);
						} else if(element == 'word') {
							self.generatePermanentWordWithWordcloud(dataAnalytics);
						}
					}
				}
			} else {
				// Reinicio para las preguntas tipo 'P'
				indexP = 0;
				arrayP = [];

				// Palabras (1) o frases (2)
				let wordsOrPhrases = 2;

				if(question.typeQuestion[i] == 'S' || question.typeQuestion[i] == 'Q') {
					wordsOrPhrases = 1;
				}

				// Ruta WordCloud
				let src = self.parameters.wordCloudURL + '/?a=' + self.parameters.survey + '&b=' + question.questionID[i] + '&c=&d=&e=&f=&g=' + self.parameters.primaryColor + '&h=' + self.parameters.secundaryColor + '&i=' + wordsOrPhrases + '&j=' + self.parameters.numberWordsWordcloud + '&k=&l=&m=&n=&o=';

				window.addEventListener('message', loadWordCloud);
				function loadWordCloud(event) {
					let wordcloud = '1';
					if(question.typeQuestion[i] == 'O' || question.typeQuestion[i] == 'P') {
						wordcloud = '2';
					}

					let obj = {
						wordCloud: wordcloud,
						element: event.data
					};

					wordcloudImgArray.push(obj);

					window.removeEventListener('message', loadWordCloud);

					i++;
					setTimeout(function() {
						if(i < question.wordCloud.length) {
							// Control para la cancelación de reporte
							if(self.continueReport) {
								createWordcloud(dataAnalytics, i);
							} else {
								return false;
							}
						} else {
							dataAnalytics.wordcloudImgArray = wordcloudImgArray;

							if(element == 'powerpoint') {
								self.generatePermanentPowerpointWithWordcloud(dataAnalytics);
							} else if(element == 'word') {
								self.generatePermanentWordWithWordcloud(dataAnalytics);
							}
						}
					}, 500);
				}
				$('#result_word_cloud').attr('src', src);
			}*/
		}

		// Control para la cancelación de reporte
		if(self.continueReport) {
			createWordcloud(dataAnalytics, i);
		} else {
			return false;
		}
	}

	// Generar reporte en powerpoint
	generatePermanentPowerpointWithWordcloud(dataAnalytics) {
		let self = this;

		// RSC53: Paso 3 de 3
		// RSC54: Generando documento...
		let steps = pf.const.language.RSC53 + '<br>' + pf.const.language.RSC54;
		$(`#downloadCardText_${self.idReport}`).html(steps);

		let parameters = {
			idTenant: sessionStorage['STCMBackEnd:idTenant'],
			colorsHex: self.parameters.colorsHex,
			survey: self.parameters.survey,
			user: self.parameters.user,
			typeColors: self.parameters.typeColors,
			param4: self.parameters.numPregPerf,
			idmision: self.parameters.idmision,
			stampMision: self.parameters.stampMision,
			project: self.parameters.project,
			briefing: self.parameters.briefing,
			fontName: self.parameters.fontName,
			fontSize: self.parameters.fontSize,
			reportData: JSON.stringify(dataAnalytics),
			plantillaReportes: self.parameters.plantillaReportes
		};
		ajaxComunCallWithCallback('generatePermanentPowerpointWithWordcloud', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				// Control para la cancelación de reporte
				if(!self.continueReport) {
					return false;
				}

				if(self.reports.word) {
					self.generatePermanentWordWithWordcloud(dataAnalytics);
				} else {
					self.finishReports();
				}
			}
		}, false);
	}

	// Generar reporte en word
	generatePermanentWordWithWordcloud(dataAnalytics) {
		let self = this;

		// RSC53: Paso 3 de 3
		// RSC54: Generando documento...
		let steps = pf.const.language.RSC53 + '<br>' + pf.const.language.RSC54;
		$(`#downloadCardText_${self.idReport}`).html(steps);

		let parameters = {
			idTenant: sessionStorage['STCMBackEnd:idTenant'],
			colorsHex: self.parameters.colorsHex,
			survey: self.parameters.survey,
			user: self.parameters.user,
			typeColors: self.parameters.typeColors,
			param4: self.parameters.numPregPerf,
			idmision: self.parameters.idmision,
			stampMision: self.parameters.stampMision,
			project: self.parameters.project,
			briefing: self.parameters.briefing,
			fontName: self.parameters.fontName,
			reportData: JSON.stringify(dataAnalytics)
		};
		ajaxComunCallWithCallback('generatePermanentWordWithWordcloud', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				// Control para la cancelación de reporte
				if(!self.continueReport) {
					return false;
				}

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

	// Generar reporte dinámico en powerpoint
	generateDinamicReport() {
		let self = this;

		self.idReport = Math.floor(Date.now() / 1000);

		$('#show-generating-reports').css('visibility', 'visible');
		let report = {
			name: self.parameters.mission,
			id: self.idReport,
			title: pf.const.language.RSC1941,
			subtitle: pf.const.language.RSC49,
			cancelButton: true
		}
		CardGeneratorController.addNotification(report);

		$(`#cancelDowload${self.idReport}`).off().on('click', (e)=>{
			e.preventDefault();
			self.cancelAjax();
		});

		let parameters = {
			idTenant: sessionStorage['STCMBackEnd:idTenant'],
			missionName: self.parameters.mission,
			reportData: JSON.stringify(self.parameters.reportData),
			defaultTemplate: JSON.stringify(self.parameters.defaultTemplate)
		};
		ajaxComunCallWithCallback('generateDinamicReport', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				$(`#downloadCardTitle_${self.idReport}`).html(pf.const.language.RSC55 + ' - ' + self.parameters.mission);
				$(`#downloadCardText_${self.idReport}`).html(pf.const.language.RSC1380);
				$(`#${self.idReport}`).find('#statusIcon').html(stcmbackend.svg.checkCircleWithoutColor);
				$(`#${self.idReport}`).find('#statusIcon').css('color', 'green');
				$(`#${self.idReport}`).find(`#buttonWrapper${self.idReport}`).html(`
					<button id="cancelGeneratedReport" type="button" class="btn new-style-cancel">${pf.const.language.RSC57}</button>
					<button id="dowloadGeneratedReport" type="button" class="btn new-style-accept">${pf.const.language.RSC56}</button>
				`);
				$(`#${self.idReport}`).removeClass('runningReport');

				CardGeneratorController.updateIcon();
				CardGeneratorController.showOnScreenNotification(self.idReport, pf.const.language.RSC55, 'check-circle');

				$(`#${self.idReport}`).find('#dowloadGeneratedReport').off().on('click', ()=>{
					// Creación de elemento para descarga
					let link = document.createElement('a');
					link.setAttribute('href', stcm.const.downloads + 'reports/dinamic/' + ajaxReturn.result);
					link.setAttribute('download', 'dynamic_sampling.pptx');
					document.body.appendChild(link);
					link.click();
					link.remove();

					CardGeneratorController.deleteNotification(self.idReport);

					let parameters = {
						filename: 'reports/dinamic/' + ajaxReturn.result
					};
					ajaxComunCallWithCallbackVoid('deleteFile', parameters);
				});
				$(`#${self.idReport}`).find('#cancelGeneratedReport').off().on('click', ()=>{
					CardGeneratorController.deleteNotification(self.idReport);

					let parameters = {
						filename: 'reports/dinamic/' + ajaxReturn.result
					};
					ajaxComunCallWithCallbackVoid('deleteFile', parameters);
				});
			}
		});
	}

	// Cancelar el proceso de creación de reportes
	cancelAjax(deleteNotification = true) {
		let self = this;

		self.ajax = true;
		self.continueReport = false;

		if(deleteNotification) {
			CardGeneratorController.deleteNotification(self.idReport);
		}
	}

	// Finalizar proceso de generación de reportes
	finishReports() {
		let self = this;

		let content = pf.const.language.RSC1380;

		if(self.errorsReports.images || self.errorsReports.excel || self.errorsReports.wc || self.errorsReports.ppt || self.errorsReports.word) {
			content += '<p>' + pf.const.language.RSC546 + ':</p><ul>';
		}

		if(self.errorsReports.images) {
			content += '<li>' + pf.const.language.RSC544 + '</li>';
		}
		if(self.errorsReports.excel) {
			content += '<li>' + pf.const.language.RSC541 + '</li>';
		}
		if(self.errorsReports.wc) {
			content += '<li>' + pf.const.language.RSC542 + '</li>';
		}
		if(self.errorsReports.ppt) {
			content += '<li>' + pf.const.language.RSC538 + '</li>';
		}
		if(self.errorsReports.word) {
			content += '<li>' + pf.const.language.RSC536 + '</li>';
		}

		if(self.errorsReports.images || self.errorsReports.excel || self.errorsReports.wc || self.errorsReports.ppt || self.errorsReports.word) {
			content += '</ul>';
		}

		if(self.continueReport) {
			$(`#downloadCardTitle_${self.idReport}`).html(pf.const.language.RSC55 + ' - ' + self.parameters.nameMission);
			$(`#downloadCardText_${self.idReport}`).html(content);
			$(`#${self.idReport}`).find('#statusIcon').html(stcmbackend.svg.checkCircleWithoutColor);
			$(`#${self.idReport}`).find('#statusIcon').css('color', 'green');
			$(`#${self.idReport}`).find(`#buttonWrapper${self.idReport}`).html(`
				<button id="cancelGeneratedReport" type="button" class="btn new-style-cancel">${pf.const.language.RSC57}</button>
				<button id="dowloadGeneratedReport" type="button" class="btn new-style-accept">${pf.const.language.RSC56}</button>
			`);
			$(`#${self.idReport}`).removeClass('runningReport');

			CardGeneratorController.updateIcon();
			CardGeneratorController.showOnScreenNotification(self.idReport,pf.const.language.RSC55, 'check-circle');

			$(`#${self.idReport}`).find('#dowloadGeneratedReport').off().on('click', ()=>{
				let parameters = {
					name: self.parameters.idmision,
					survey: self.parameters.survey,
					stampMision: self.parameters.stampMision,
					project: self.parameters.project,
					reports: JSON.stringify(self.reports)
				};
				ajaxComunCallWithCallback('downloadPermanentReports', parameters, function(ajaxReturn) {
					if(ajaxReturn) {
						// Creación de elemento para descarga
						let link = document.createElement('a');
						link.setAttribute('href', stcm.const.downloads + ajaxReturn.result);
						link.setAttribute('download', ajaxReturn.name);
						document.body.appendChild(link);
						link.click();
						link.remove();

						CardGeneratorController.deleteNotification(self.idReport);
					}
				});
			});
			$(`#${this.idReport}`).find('#cancelGeneratedReport').off().on('click', ()=>{
				CardGeneratorController.deleteNotification(this.idReport);
			});
		}
	}
}