let ClientsEditController = {
	countries: null,
	endpoint: null,
	client: null,
	licencesData: [],
	countriesToAdd: [],
	GoogleMapsAPI: null,
	AzureTranscriptionAPI: null,
	AzureImageAPI: null,
	AzureTranslatorAPI:null,
	TwilioSMSAPI: null,

	countryModal: null,

	resetData() {
		let self = this;

		self.countries = null;
		self.client = JSON.parse(sessionStorage.getItem('idClient'));
		self.endpoint = self.client.endpoint;
		self.licencesData = [];
		self.countriesToAdd = [];
		self.GoogleMapsAPI = self.client.GoogleMapsAPI;
		self.AzureTranscriptionAPI = self.client.AzureTranscriptionAPI;
		self.AzureImageAPI = self.client.AzureImageAPI;
		self.AzureTranslatorAPI = self.client.AzureTranslatorAPI;
		self.TwilioSMSAPI = self.client.TwilioSMSAPI;

		self.countryModal = null;
	},

	setEvents() {
		let self = this;

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

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

		// Opciones de header
		let jsonsubopt = {
			back: 'back',
			save: 'save'
		};

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

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

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

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

		self.resetData();
		self.loadLang();
		self.loadClientData();

		$('#clientName').text(self.client.nombre);
		$('#total').text(self.client.licences);
		$('#totalcountry').text(self.client.licences);

		// Exportar tabla
		$('#exportTablas').off().on('click', function() {
			$('#resultTable .buttons-excel').trigger('click');
		});

		// Guardar
		$('#save').off().on('click', function() {
			self.setAllCustomerDetails();
		});

		// Añadir pais mediante seleccion modal
		// País
		self.countryModal = new TableCountries(0, 'clientesEdit');

		$('#newCountry').off().on('click', function() {
			self.countryModal.setEvents('tableModal', true);
		});

		stcmbackend.gestionclientes.sharedEvents();
	},

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

	loadClientData() {
		let self = this;

		let parameters = {
			id: self.endpoint
		};
		ajaxComunCallWithCallback('getAllCustomerDetails', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.countries = ajaxReturn.result;
				self.getCountries();

				// Tablas de resultados
				self.renderData();
			}
		});
	},

	renderData() {
		let self = this;

		$('#resultTable').show();

		let table = stcmbackend.gestionclientes.generateHeadersTablePaisesCliente();

		let assignedLicenses = 0;

		for(let i = 0; i < self.countries.length; i++) {
			table += stcmbackend.gestionclientes.renderClientePais(self.countries[i]);

			assignedLicenses += parseInt(self.countries[i].licencias);
		}

		table += `
			</tbody>
		`;

		// Total de licensias asignadas
		$('#totalcountry').text(assignedLicenses);

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

			if(title == 'enabled' || title == 'registro') {
				value = optionsSelectAllYesNo();
			} else if(title == 'edit' || title == 'delete' || title == 'icono') {
				value = `<input type="text" class="form-control form-control-sm" disabled>`;
			}

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

		let dataTable = $('#registers').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			pageLength: 25,
			autoWidth: false,
			columnDefs: [
				{width: '30px', orderable: false, targets: 0}
			],
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC2242,
				className: 'd-none',
				title: pf.const.language.RSC2242,
				exportOptions: {
					columns: [0, 1, 2]
				},
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
			aaSorting: []
		});

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

		// Apply the search
		applyTheSearch(dataTable, 'filtersResult');

		// Exportar tabla
		$('#export').off().on('click', function() {
			$('#resultTable .buttons-excel').trigger('click');
		});

		self.tableEvents();

		$('#resultTable').on('draw.dt', function() {
			self.tableEvents();
		});
	},

	tableEvents() {
		let self = this;

		$('.licInput').off().blur(function() {
			let licencias = 0;
			$('.licInput').each(function() {
				licencias += parseInt($(this).val() || 0);
				$('#totalcountry').text(licencias);
			});
		})
	},

	setAllCustomerDetails() {
		let self = this;

		let licencias = 0;
		let licenciaPais = '';
		self.licencesData = [];
		$('.licInput').each(function() {
			licenciaPais = $(this).val() || 0;
			licencias += parseInt(licenciaPais);
			self.licencesData.push($(this).data('pais') + ';' + licenciaPais);
		});

		if(self.client.licences < licencias || self.client.licences > licencias) {
			//mostrar aviso para indicar que se pasan de x a z licencias para el cliente
			let objInfo = {
				accept: {
					text: pf.const.language.RSC141
				},
				cancel: {
					text: pf.const.language.RSC57
				}
			};
			let alertTitle = pf.const.language.RSC2242;
			let alertText = pf.const.language.RSC2243;
			alertText = alertText.replace('%1', self.client.licences);
			alertText = alertText.replace('%2', licencias);
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				self.requestSetAllCustomerDetails(licencias);
			}, function() {});
		}
		else self.requestSetAllCustomerDetails(licencias);
	},

	requestSetAllCustomerDetails(total) {
		let self = this; 

		let parameters = {
			id: self.endpoint,
			licencias: JSON.stringify(self.licencesData),
			total: total,
			GoogleMapsAPI: self.GoogleMapsAPI,
			AzureTranscriptionAPI: self.AzureTranscriptionAPI,
			AzureImageAPI: self.AzureImageAPI,
			AzureTranslatorAPI: self.AzureTranslatorAPI,
			TwilioSMSAPI: self.TwilioSMSAPI
		};
		ajaxComunCallWithCallback('setAllCustomerDetails', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				if(ajaxReturn.result.result === 'All lic. by country has setted succesfully.') {
					let successTitle = pf.const.language.RSC2242;
					let successContent = pf.const.language.RSC1668;
					pf.utils.showInfoDialog(successTitle, successContent);

					window.location.href = '#!clientes';
				} else {
					let errorTitle = pf.const.language.RSC61;
					let errorContent = ajaxReturn.result;
					pf.utils.showInfoDialog(errorTitle, errorContent);
				}
			}
		});
	},

	getCountries() {
		let self = this;

		ajaxComunCallWithCallback('getPaisesEnabled', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				let size = ajaxReturn.result.length;
				for(let i = 0; i < size; i++) {
					if(self.countries.find(o => o.pais === ajaxReturn.result[i].isocode) === undefined) {
						self.countriesToAdd.push(ajaxReturn.result[i]);
					}
				}

				self.countryModal.data = self.countriesToAdd;
			}
		});
	},

	clickEvents(data) {
		let self = this;
		
		let obj = {
			pais: data.isocode,
			descripcion: data.descripcion,
			licencias: 0
		};
		self.countries.push(obj);
		self.renderData();
	}
};