<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:th="http://www.thymeleaf.org">

<head th:replace="~{layouts/common.html :: head}"></head>

<body id="page-top">

	<!-- Navigation -->
	<nav th:replace="~{layouts/common.html :: navbar}"></nav>
 
 	<!-- Content -->
	<div class="content uv-content d-flex" id="uv-wrapper">
		<div class="bg-light border-right" id="uv-sidebar-wrapper" th:replace="~{layouts/sidebar.html :: sidebar}"></div>
		
		<div class="container uv-home-section navVisible" id="uv-content-wrapper">
		
			<div class="uv-loading-spinner" th:text="#{global.loading}"></div>
			<div class="col-sm-12"></div>
			<div class="uv-container">
				<div class="uv-table-group-procedure-info" style="margin-bottom:20px;">
					<div class="uv-table-title">
						<h6 class="uv-table-header-h6">Editor de plantillas</h6>
						<hr class="uv-procedure-hr">
					</div>
				</div>
				
				
				<div class="uv-table-group">
					<div class="uv-table-group">
						<label>Plantilla</label>
						<select class="selectpicker" id="templateSelector" name="procedure" data-live-search="true" data-width="100%" data-actions-box="true" th:attr="data-none-selected-text=#{global.selectors.noData}" onchange="formEdit();">
					        <option th:each="item : ${templates}" th:text="${#locale.language} == 'es' ? '['+${item.codi}+'] {v'+${item.versio}+'} ['+${item.ambit}+'] '+${item.nomCas}:${item.codi}+' {v'+${item.versio}+'} ['+${item.ambit}+'] '+${item.nomVal}" th:attr="value=${item.idPlantilla}"></option>
					    </select>
					</div>
					<br>
					<span class="btn btn-warning pointer" onclick="formTest()" data-toggle="modal" data-target="#testTemplateModal"><i class="fas fa-file"></i> <span th:text="Probar">Probar</span></span>
					<hr class="uv-procedure-hr">
				</div>
				
				<div class="uv-table-group" id="formFields">
					
				</div>
				
				<div class="uv-table-group">
					<textarea id="editor" name="evidencia_text"></textarea>
				</div>
				
			</div>
		</div>
	</div>
	
	<div class="modal fade" id="searchIndsModal" tabindex="-1" role="dialog" aria-labelledby="searchIndsModal" aria-hidden="true">
	  <div class="modal-dialog modal-lg">
	    <div class="modal-content">
		    <div class="modal-header">
		        <h5 class="modal-title">Buscar indicadores</h5>
		        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
		        	<span aria-hidden="true">&times;</span>
		        </button>
	        </div>
	        <div class="modal-body">
	        	<div class="container-fluid">
			    	<form id="searchIndForm" action="javascript:void(0)" style="margin-top:25px;">
						<div class="form-group">
							<label>Indicador/Valor de encuesta</label>
							<select class="selectpicker" id="indSelector" data-live-search="true" data-width="100%" data-actions-box="true" required>
						        <option th:each="item : ${inds}" th:text="${item}" th:attr="value=${item}"></option>
						    </select>
						</div>
					</form>
				</div>
			</div>
			<div class="modal-footer">
		        <button type="button" class="btn btn-secondary" data-dismiss="modal" th:text="#{global.cancel}">Cancelar</button>
		        <span class="btn btn-success" onclick="insert_data();">Insertar</span>
	        </div>
	    </div>
	  </div>
	</div>
	
	<div class="modal fade" id="testTemplateModal" tabindex="-1" role="dialog" aria-labelledby="searchIndsModal" aria-hidden="true">
	  <div class="modal-dialog modal-lg">
	    <div class="modal-content">
		    <div class="modal-header">
		        <h5 class="modal-title">Probar plantilla</h5>
		        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
		        	<span aria-hidden="true">&times;</span>
		        </button>
	        </div>
	        <div class="modal-body">
	        	<div class="container-fluid">
			    	<div class="uv-table-group-procedure">
						<label th:text="#{admin.instances.selector.center}">Centre(s)</label>
						<select class="selectpicker" id="centersSelector" name="center" data-live-search="true" data-width="100%" data-actions-box="true" th:attr="data-none-selected-text=#{global.selectors.noData}" required>
					        <option th:each="item : ${centers}" th:text="${#locale.language} == 'es' ? ${item.text}:${item.text2}" th:attr="value=${item.value}"></option>
					    </select>
					</div>
					<div class="uv-table-group-procedure">
						<label th:text="#{admin.instances.selector.titulation}">Titulació(ns)</label>
						<select class="selectpicker" id="titulationsSelector" name="titulation" data-live-search="true" data-width="100%" data-actions-box="true" required>
					        <option th:each="item : ${titulations}" th:text="${#locale.language} == 'es' ? ${item.text}:${item.text2}" th:attr="value=${item.value}"></option>
					    </select>
					</div>
					<div class="uv-table-group-procedure">
						<label th:text="#{admin.instances.selector.curs}">Curso</label>
						<select class="selectpicker" id="cursSelector" name="curs" data-live-search="true" data-width="100%" data-actions-box="true" required>
							<option th:each="year : ${#numbers.sequence(2020, #dates.year(#dates.createNow()))}"
							    th:value="${year}" th:text="${year}">
							</option>
						</select>
					</div>
				</div>
			</div>
			<div class="modal-footer">
		        <button type="button" class="btn btn-secondary pointer" data-dismiss="modal" th:text="#{global.cancel}">Cancelar</button>
		        <span class="btn btn-success pointer" onclick="testTemplate();">Probar</span>
	        </div>
	    </div>
	  </div>
	</div>

	<!-- contactModal -->
	<div th:replace="~{layouts/common.html :: contactModal}"></div>
	
	<!-- Footer -->
	<footer class="uv-footer uv-footer-text" th:replace="~{layouts/common.html :: footer}"></footer>
	
	<script th:src="@{/js/jquery/jquery.min.js}"></script>
	<script th:src="@{/js/popper.js}"></script>
	<script th:src="@{/js/bootstrap/bootstrap.min.js}"></script>
	<script th:src="@{/js/fa/all.js}"></script>
	<script th:src="@{/js/jquery/jquery.dataTables.min.js}"></script>
	<script th:src="@{/js/jquery/jquery.dataTables.responsive.min.js}"></script>
	<script th:src="@{/js/jquery/jquery.dataTables.rowReorder.min.js}"></script>
	<script th:src="@{/js/bootstrap/dataTables.bootstrap4.min.js}"></script>
	<script th:src="@{/js/jquery-easing/jquery.easing.min.js}"></script>
	<script th:src="@{/js/saic.js}"></script>
	<script th:src="@{/js/datepicker/bootstrap-datepicker.min.js}"></script>
	<script th:src="@{/js/bootstrap-select/bootstrap-select.js}"></script>
	<script th:src="@{/js/bootstrap-select/i18n/defaults-es_ES.js}" th:if="${#locale.language} == 'es'"></script>
	<script th:src="@{/js/bootstrap-select/i18n/defaults-ca_CA.js}" th:if="${#locale.language} != 'es'"></script>
	<script src="https://cdnjs.cloudflare.com/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
  
	<script type="text/javascript">
		
	
		var opts = { margin: [0, 12, 0, 12] };
		var worker = html2pdf();
		worker.set(opts);
		var action;
	
		$( document ).ready(function(){ 
			layout = new Layout("");
			layout.initTableLayout({paging:false});
			layout.closeLoadingSpinner(".uv-loading-spinner");
			$('#centersSelector').val('').trigger('change');
			$('#centersSelector').change(completeTitulations);
			
			tinymce.init({ 
				selector: '#editor',
				plugins: 'preview visualblocks visualchars fullscreen image link media table pagebreak nonbreaking anchor advlist lists charmap quickbars checklist',
				menubar: 'help',
				toolbar: 'preview topdf | fullscreen ',
				content_style: "body { font-size: 10pt; }",
				body_class: 'mceNonEditable',
				object_resizing : ":not(table)",
				font_size_formats: '8pt 9pt 10pt 11pt 12pt 14pt 16pt 18pt 24pt',
				setup: (editor) => {
					
					editor.on('keydown', function(e) {
						if (e.keyCode == 8 || e.keyCode == 46) { //backspace and delete keycodes
		                    try {
		                        var elem = tinymce.activeEditor.selection.getNode(); //current caret node
		                        if (elem.classList.contains("mceNonEditable")) {
		                        	e.preventDefault();
	                                return false;
		                        }
		                    } catch (e) {console.log(e);}
		                }
					});
					
					editor.on('TableModified', function(e) {
						editor.setContent(editor.getContent());	      
					});
					
					editor.ui.registry.addIcon('save', '<i style="font-size:125%;" class="fas fa-save"></i>')
					
					editor.ui.registry.addButton('insert-data', {
						icon: 'code-sample',
						tooltip: 'Insertar indicador/encuesta',
				      	onAction: function(_){ 
				      		$('#searchIndsModal').modal('show');
				      	}
				    });
						
					editor.ui.registry.addButton('topdf', {
						icon: 'print',
						tooltip: 'Imprimir a PDF',
				      	onAction: function(_){ 
				      		print_to_pdf(editor.getContent());
				      	}
				    });
					
					editor.ui.registry.addButton('btn-editable', {
						icon: 'unlock',
						tooltip: 'Desbloquear contenido',
				      	onAction: function(_){ 
				      		var ns = $(editor.selection.getSelectedBlocks()).each(function(b){
				      			$(console.log($(this)))
				      			$(this).removeClass('mceEditable').removeClass('mceNonEditable').addClass('mceEditable')
				      		});
				      		editor.setContent(editor.getContent());	      		
				      	}
				    });
					
					editor.ui.registry.addButton('btn-noneditable', {
						icon: 'lock',
						tooltip: 'Bloquear contenido',
				      	onAction: function(_){ 
				      		var ns = $(editor.selection.getSelectedBlocks()).each(function(b){
				      			$(console.log($(this)))
				      			$(this).removeClass('mceEditable').removeClass('mceNonEditable').addClass('mceNonEditable')
				      		});
				      		editor.setContent(editor.getContent());
				      	}
				    });
					
					editor.on('init', function(e) {
			            formEdit();
			        });
				},
				codesample_languages: [
				    { text: 'Valor de indicador o encuesta', value: 'markup' },
				  ],
				save_onsavecallback: function(){save_content();},
				autosave_ask_before_unload: true,
				autosave_interval: '20s',
				autosave_prefix: '{path}{query}-{id}-',
				autosave_restore_when_empty: false,
				autosave_retention: '2m',
				image_advtab: true,
				link_list: [
				  { title: 'My page 1', value: 'https://www.tiny.cloud' },
				  { title: 'My page 2', value: 'http://www.moxiecode.com' }
				],
				image_list: [
				  { title: 'My page 1', value: 'https://www.tiny.cloud' },
				  { title: 'My page 2', value: 'http://www.moxiecode.com' }
				],
				image_class_list: [
				  { title: 'None', value: '' },
				  { title: 'Some class', value: 'class-name' }
				],
				importcss_append: true,
				file_picker_callback: (callback, value, meta) => {
				  /* Provide file and text for the link dialog */
				  if (meta.filetype === 'file') {
				    callback('https://www.google.com/logos/google.jpg', { text: 'My text' });
				  }
				
				  /* Provide image and alt text for the image dialog */
				  if (meta.filetype === 'image') {
				    callback('https://www.google.com/logos/google.jpg', { alt: 'My alt text' });
				  }
				
				  /* Provide alternative source and posted for the media dialog */
				  if (meta.filetype === 'media') {
				    callback('movie.mp4', { source2: 'alt.ogg', poster: 'https://www.google.com/logos/google.jpg' });
				  }
				},
				table_class_list: [
				    {title: 'Normal', value: ''},
				    {title: 'Tabla editable', value: 'mceEditable'},
				    {title: 'Tabla editable A4 H', value: 'mceEditable mceTableA4H'},
				    {title: 'Tabla editable A4 V', value: 'mceEditable mceTableA4V'},
				    {title: 'Tabla no editable', value: 'mceNonEditable'},
				    {title: 'Tabla comentario', value: 'mceNonEditable pdfignore'}
				],
				table_appearance_options: true,
				height: 600,
				image_caption: true,
				quickbars_selection_toolbar: 'bold italic | quicklink h2 h3 blockquote quickimage quicktable',
				toolbar_mode: 'sliding',
				contextmenu: 'link image table',
			});		
			tinymce.get('id').setMode('readonly');
			
		});
		
		function completeTitulations(){
			if ($('#centersSelector').val() !== null && $('#centersSelector').val() !== ''){
				var params = {'center':$('#centersSelector').val()};
				$.post("/get/titulations", params, function(data){ 
					$("#titulationsSelector").html(data).selectpicker('refresh'); 
					$('#titulationsSelector').val('').trigger('change');
				});
			}
		}
		
		function save_content(){		
			if(action === "edit"){
				$.post("/template/edit", 
				{id: $('#templateSelector').val(),
					text:tinymce.activeEditor.getContent(),
					versio:$('#versioInput').val(),
					nomCas:$('#nomCasInput').val(),
					nomVal:$('#nomValInput').val(),
					ambit:$('#ambitInput').val()},
				function(d){
						if(d == '0'){
							alert('Ya existe la combinación Código-Versión-Ámbito');
						}
						else{
							alert('Acción realizada correctamente');
						}
						
					}
				);
			}else{
				$.post("/template/save", 
				{codi:$('#codiInput').val(),
					versio:$('#versioInput').val(),
					nomCas:$('#nomCasInput').val(),
					nomVal:$('#nomValInput').val(),
					ambit:$('#ambitInput').val(),
					text:tinymce.activeEditor.getContent()},
				function(d){
						if(d == '0'){
							alert('Ya existe la combinación Código-Versión-Ámbito');
						}
						else{
							alert('Acción realizada correctamente');
						}
						
					}
				);
			}
		}
		
		function print_to_pdf(content){
			$('<form id="tmpDownloadForm" method="post" action="/pdf/preview" target="_blank">' +
			  	'<textarea id="tmpDownloadContent" type="hidden" name="content">' +
			  		tinymce.activeEditor.getContent() +
			  	'</textarea>' +
			  '</form>')
			.appendTo('body')
			.submit()
			.remove();	
		}
		
		function insert_data(){
			tinymce.activeEditor.selection.setContent('{{'+$('#indSelector').val()+'}}');
			$('#searchIndsModal').modal('hide');
		}
		
		function formEdit(){
			$.post("/template/form", {id:$('#templateSelector').val(), action:"edit"}, function(rawData){ 
				var form = $($.parseHTML(rawData));
				$(form).find('#editorContent')[0].remove()
				var data = $($.parseHTML(rawData)).find('#editorContent').html();
				$('#formFields').html('');
				$(form).appendTo($('#formFields'));
				tinymce.activeEditor.setContent(data);
				action = "edit";
				$('#formFields').show();
			});
		}

		function formNew(){
			$.post("/template/form", {id:0, action:"new"}, function(rawData){ 
				var form = $($.parseHTML(rawData));
				$(form).find('#editorContent')[0].remove()
				var data = $($.parseHTML(rawData)).find('#editorContent').html();
				$('#formFields').html('');
				$(form).appendTo($('#formFields'));
				tinymce.activeEditor.setContent(data);
				action = "new";
				$('#formFields').show();
			});
		}
		
		function formDuplicate(){
			$.post("/template/form", {id:$('#templateSelector').val(), action:"duplicate"}, function(rawData){ 
				var form = $($.parseHTML(rawData));
				$(form).find('#editorContent')[0].remove()
				var data = $($.parseHTML(rawData)).find('#editorContent').html();
				$('#formFields').html('');
				$(form).appendTo($('#formFields'));
				tinymce.activeEditor.setContent(data);
				action = "duplicate";
				$('#formFields').show();
			});
		}
		
		function formDelete(){
			$.ajax({
			     url: "/template/form",
			     type: "DELETE",
			     data: {id:$('#templateSelector').val()}
			  })
			  .done(function(d){
					if(d == '1'){
						location.reload();
					}
					else{
						alert('La plantilla está asignada a un procedimiento. No se puede eliminar.');
					}
			  });
		}
		
		function testTemplate(){
			var url = "/admin/editor/test?idPlantilla="+$('#templateSelector').val()+"&idTitulacio="+$('#titulationsSelector').val()+"&idCentre="+$('#centersSelector').val()+"&curs="+$('#cursSelector').val();
			window.open(url, '_blank').focus();	
		}
			
		
	</script>

</body>

</html>
