stcmbackend.addons = {
	applyEvents(self, modal) {
		// Volver a Listas de AddOns
		$('#back').off().on('click', function() {
			window.location.href = '#!addons';
		});

		// Ocultar cubo de basura
		$('#countryDelete').hide();

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

		// Limpiar País
		$('#countryDelete').on('click', function() {
			$('#pais').val('');
			$('#countryDelete').hide();
		});

		// Si se marca 'Registro', se marca pantalla completa y no se puede desmarcar
		$('#register').off().on('change', function() {
			let checked = $('#register').prop('checked');

			if(self.sections.length > 1 && checked) {
				$('#register').prop('checked', false);

				let warningTitle = pf.const.language.RSC1246;
				let warningContent = pf.const.language.RSC2332;
				pf.utils.showInfoDialog(warningTitle, warningContent);
			} else {
				if(checked) {
					$('#fullScreen').prop('checked', true);
					$('#fullScreen').prop('disabled', true);
					$('#fullscreenWarning').removeClass('d-none');
				} else {
					$('#fullScreen').prop('disabled', false);
				}
			}
		});

		// Si se marca pantalla completa aparece el aviso
		$('#fullScreen').off().on('change', function() {
			let checked = $('#fullScreen').prop('checked');

			if(checked) {
				$('#fullscreenWarning').removeClass('d-none');
			} else {
				$('#fullscreenWarning').addClass('d-none');
			}
		});

		// Añadir sección
		$('#newSeccion').off().on('click', function() {
			let size = self.sections.length;
			if(size > 0 && $('#register').prop('checked')) {
				let warningTitle = pf.const.language.RSC1246;
				let warningContent = pf.const.language.RSC2332;
				pf.utils.showInfoDialog(warningTitle, warningContent);
			} else {
				let obj = stcmbackend.addons.sections.createNewAdonSectionObj();
				self.sections.push(obj);
				stcmbackend.addons.sections.tableSections(self);
			}
		});

		// Añadir DeepLink
		$('#newDeepLink').off().on('click', function() {
			let obj = stcmbackend.addons.deeplinks.createNewAdonDeepLinkObj();

			self.deeplinks.push(obj);
			stcmbackend.addons.deeplinks.tableDeepLinks(self);
		});
	},

	sections: {
		generateHeadersTableAddonsSections() {
			let arrayTexts = [
				pf.const.language.RSC1556,
				pf.const.language.RSC178,
				''
			];

			let headersInfo = {
				atr: {
					title: arrayTexts
				},
				text:arrayTexts
			};

			return stcmbackend.tables.headers.generateTheadWithTable('tableSections', stcmbackend.tables.tableClass + ' tRegs', headersInfo);
		},

		renderSection(object, i) {
			return `
				<tr data-id="${i}">
					<td class="text-truncate p-1">
						<span class="d-none">${object.idSection}</span>
						<input id="idSection${i}" type="text" class="form-control idSectionInput" value="${object.idSection}" title="${object.idSection}">
					</td>
					<td class="p-1">
						<span class="d-none">${object.description}</span>
						<div class="input-group">
							<input id="descriptionSec${i}" type="text" class="form-control descriptionInput" value="${object.description}" title="${object.description}">
							<div class="input-group-append">
								<button id="icon-button-${i}" type="button" class="btn btn-outline-secondary iconpicker-component" disabled></button>
								<button id="icons-${i}" type="button" class="icp icp-dd btn btn-outline-secondary dropdown-toggle iconsSection" data-selected="fa-adjust" data-toggle="dropdown" data-index="${i}">
									<span class="caret"></span>
									<span class="sr-only"></span>
								</button>
								<div class="dropdown-menu wi-233" data-index="${i}"></div>
							</div>
						</div>
					</td>
					<td class="text-truncate text-center" title="${pf.const.language.RSC226}">
						<span class="c-pointer deleteSelection" data-id="${i}">
							${stcmbackend.svg.bigTrash}
						</span>
					</td>
				</tr>
			`;
		},

		createNewAdonSectionObj() {
			return {
				idSection: '',
				idSectionOld: '',
				description: '',
				section_icon: 'fa-light fa-adjust'
			};
		},

		tableSections(self) {
			let table = stcmbackend.addons.sections.generateHeadersTableAddonsSections();

			let size = self.sections.length;
			if(size < 1) {
				let obj = stcmbackend.addons.sections.createNewAdonSectionObj();
				self.sections.push(obj);
				size = 1;
			}

			for(let i = 0; i < size; i++) {
				table += stcmbackend.addons.sections.renderSection(self.sections[i], i);
			}

			table += `
					</tbody>
				</table>
			`;

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

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

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

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

			stcmbackend.addons.sections.sectionsTableEvents(self);
		},

		sectionsTableEvents(self) {
			// Restricciones de carácteres por tecla para input de idSection
			$('.idSectionInput').off().on('keypress', function(e) {
				// Parámetros: tecla, warningTitle, warningContent y pattern si no es el general
				let result = characterRestrictionsPerKey(e.keyCode, pf.const.language.RSC375, pf.const.language.RSC1830, /[a-z0-9_]/i);

				return result;
			});

			// Restricciones de carácteres por pegado para input de idSection
			$('.idSectionInput').on('paste', function() {
				// Parámetros: elemento, warningTitle, warningContent y pattern si no es el general
				characterRestrictionsPerPaste($(this), pf.const.language.RSC375, pf.const.language.RSC1830, /[^a-z0-9_]/gi);
			});

			// Input de idSection
			$('.idSectionInput').on('blur', function() {
				let index = $(this).attr('id').replace('idSection', '');
				let value = $(this).val();

				self.sections[index].idSection = value;
			});

			// Input de description
			$('.descriptionInput').off().on('blur', function() {
				let index = $(this).attr('id').replace('descriptionSec', '');
				let value = $(this).val();

				self.sections[index].description = value;
			});

			// fontawesome-iconpicker
			$('.iconsSection').iconpicker({
				fullClassFormatter(val) {
					return val;
				}
			});
			$('.iconpicker').css('width', '230px');

			// Restaurar iconos seleccionados
			for(let i = 0; i < self.sections.length; i++) {
				$('#icon-button-' + i).html(`<i class="${self.sections[i].section_icon}"></i>`);
			}

			// Cambio de icono
			$('.iconpicker-item').on('click', function() {
				let index = $(this).parent().parent().parent().parent().parent().data('index');
				let element = $(this).attr('title').replace('.', '');

				if(index != undefined) {
					self.sections[index].section_icon = element;
				}
			});

			// Eliminar sección
			$('#tableSections .deleteSelection').off().on('click', function() {
				let index = $(this).data('id');

				self.sections.splice(index, 1);
				stcmbackend.addons.sections.tableSections(self);
			});
		}
	},

	deeplinks: {
		generateHeadersTableAddonsDeepLinks() {
			let arrayTexts = [
				pf.const.language.RSC2120,
				pf.const.language.RSC302,
				pf.const.language.RSC1343,
				''
			];

			let headersInfo = {
				atr: {
					title: arrayTexts
				},
				text: arrayTexts
			};

			return stcmbackend.tables.headers.generateTheadWithTable('tableDeepLinks', stcmbackend.tables.tableClass + ' tRegs', headersInfo);
		},

		renderDeepLink(object, i) {
			let style = '';
			if(object.icon != '') {
				style = 'deep-link-icon';
				if(object.icon.includes('blob')) {
					// En el caso de que aún no esté guardado
					preview = object.icon;
				} else {
					preview = object.publicPath + '/' + object.icon;
				}
			} else {
				style = '';
				preview = '';
			}

			return `
				<tr data-id="${i}">
					<td class="text-truncate p-1">
						<span class="d-none">${object.id}</span>
						<input id="idDeepLink${i}" type="text" class="form-control idDeepLinkInput" value="${object.id}" title="${object.id}">
					</td>
					<td class="p-1">
						<span class="d-none">${object.description}</span>
						<div class="input-group">
							<input id="descriptionDL${i}" type="text" class="form-control descriptionInput" value="${object.description}" title="${object.description}">
						</div>
					</td>
					<td class="p-1">
						<div class="form-row">
							<div class="">
								<img id="image${i}" src="${preview}" class="${style}" alt="">
							</div>
							<div class="">
								<div class="input-group">
									<div class="input-group-append">
										<button type="button" class="btn btn-outline-secondary btn-file" data-index="${i}">
											${stcmbackend.svg.threeDots}
										</button>
									</div>
								</div>
								<div class="custom-file d-none">
									<input id="file${i}" type="file" class="custom-file-input" accept="image/*" placeholder="" data-index="${i}" aria-describedby="file${i}">
									<label for="file${i}" class="custom-file-label" data-browse="..."></label>
								</div>
							</div>
						</div>
					</td>
					<td class="text-truncate text-center" title="${pf.const.language.RSC226}">
						<span class="c-pointer deleteSelection" data-id="${i}">
							${stcmbackend.svg.bigTrash}
						</span>
					</td>
				</tr>
			`;
		},

		createNewAdonDeepLinkObj() {
			return {
				id: '',
				description: '',
				icon: '',
				file: '',
				publicPath: ''
			};
		},

		tableDeepLinks(self) {
			let table = stcmbackend.addons.deeplinks.generateHeadersTableAddonsDeepLinks();

			let size = self.deeplinks.length;
			if(size < 1) {
				let obj = stcmbackend.addons.deeplinks.createNewAdonDeepLinkObj();

				self.deeplinks.push(obj);
				size = 1;
			}

			for(let i = 0; i < size; i++) {
				table += stcmbackend.addons.deeplinks.renderDeepLink(self.deeplinks[i], i);
			}

			table += `
					</tbody>
				</table>
			`;

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

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

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

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

			stcmbackend.addons.deeplinks.tableDeepLinksEvents(self);
		},

		tableDeepLinksEvents(self) {
			// Restricciones de carácteres por tecla para input de idSection
			$('#tableDeepLinks .idDeepLinkInput').off().on('keypress', function(e) {
				// Parámetros: tecla, warningTitle, warningContent y pattern si no es el general
				let result = characterRestrictionsPerKey(e.keyCode, pf.const.language.RSC375, pf.const.language.RSC1830, /[a-z0-9_]/i);

				return result;
			});

			// Restricciones de carácteres por pegado para input de idSection
			$('#tableDeepLinks .idDeepLinkInput').on('paste', function() {
				// Parámetros: elemento, warningTitle, warningContent y pattern si no es el general
				characterRestrictionsPerPaste($(this), pf.const.language.RSC375, pf.const.language.RSC1830, /[^a-z0-9_]/gi);
			});

			// Input de idDeepLink
			$('#tableDeepLinks .idDeepLinkInput').on('blur', function() {
				let index = $(this).attr('id').replace('idDeepLink', '');
				let value = $(this).val();

				self.deeplinks[index].id = value;
			});

			// Input de description
			$('#tableDeepLinks .descriptionInput').off().on('blur', function() {
				let index = $(this).attr('id').replace('descriptionDL', '');
				let value = $(this).val();

				self.deeplinks[index].description = value;
			});

			// Cambio de icono
			$('.btn-file').click(function() {
				let i = $(this).attr('data-index');

				$('#file' + i).trigger('click');
			});

			$('.custom-file-input').change(function(event) {
				let index = $(this).attr('data-index');

				stcmbackend.addons.deeplinks.cropper.showCropController(self, event.target.files[0], index);
			});

			// Eliminar sección
			$('#tableDeepLinks .deleteSelection').off().on('click', function() {
				let index = $(this).data('id');

				self.deeplinks.splice(index, 1);
				stcmbackend.addons.deeplinks.tableDeepLinks(self);
			});
		},

		cropper: {
			initializeCrop(self, file, index) {
				$('body').append(`
					<section id="wrapLoaderDeepLink" class="animated fadeIn loaderspinner jconfirm">
						<div class="upload-demo-wrap jconfirm-box">
							<div class="jconfirm-title-c pa-10"><span class="jconfirm-title">${pf.const.language.RSC1246}</span></div>
							<div id="upload-demo"></div>
							<div class="jconfirm-buttons d-flex justify-content-end">
								<button id="cancelCrop" class="btn btn-red btn_accept" name="cancelCrop">${pf.const.language.RSC57}</button>
								<button id="acceptCrop" class="btn btn-red btn_cancel" name="acceptCrop">${pf.const.language.RSC141}</button>
							</div>
						</div>
					</section>
				`);

				$('#acceptCrop').off('click').click(function() {
					uploadCrop.croppie('result', {
						type: 'blob'
					}).then(function(blob) {
						$('#image' + index).attr('src', window.URL.createObjectURL(blob));
						$('#image' + index).attr('style', 'height: 38px; width: 38px; margin:0 10px; object-fit: contain;');
						self.deeplinks[index].icon = window.URL.createObjectURL(blob);
						self.deeplinks[index].file = blob;
						$('#wrapLoaderDeepLink').remove();
					});
				});

				$('#cancelCrop').off('click').click(function() {
					$('#wrapLoaderDeepLink').remove();
				});

				uploadCrop = $('#upload-demo').croppie({
					viewport: {
						width: 100,
						height: 100
					},
					boundary: {
						width: 300,
						height: 300
					},
					enableExif: true
				});

				uploadCrop.croppie('bind', {
					url: file
				}).then(function() {
					console.log('jQuery bind complete');
				});
			},

			showCropController(self, file, index) {
				var reader = new FileReader();

				reader.onload = function(e) {
					$('.upload-demo').addClass('ready');
					stcmbackend.addons.deeplinks.cropper.initializeCrop(self, e.target.result, index);
				}

				reader.readAsDataURL(file);
			}
		}
	}
};