<!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;margin-top:30px;cursor:auto;">
					<div class="uv-table-title">
						<h6 class="uv-table-header-h6" th:text="#{data.consolide.title}"></h6>
						<hr class="uv-procedure-hr">
						<span th:text="#{data.consolide.subtitle}"></span>
					</div>
				</div>
				<div class="uv-table-group-procedure row" style="padding:20px;">
					<select class="selectpicker" name="enquesta" data-live-search="true" data-width="100%" data-actions-box="true" th:attr="data-none-selected-text=#{global.selectors.noData}" required>
				        <option disabled selected th:text="#{data.input.select}">Selecciona un conjunto de datos</option>
				        <option value="dades_1er">[Grado] Estudiantes primero (dades_1er)</option>
				        <option value="dades_3er">[Grado] Estudiantes tercero (dades_3er)</option>
				        <option value="dades_graduats">[Grado] Graduados (dades_graduats)</option>
				        <option value="profes">[Grado] Profesores (profes)</option>
				        <option value="data">[Master] Estudiantes (data)</option>
				        <option value="data_g">[Master] Graduados (data_g)</option>
				        <option value="profes_tancades">[Master] Profesores (profes_tancades)</option>
				        <option value="doc_estud">[Doctorado] Estudiantes (doc_estud)</option>
				        <option value="doc_etesi">[Doctorado] Graduados (doc_etesi)</option>
				        <option value="doc_prof">[Doctorado] Profesores (doc_prof)</option>
				        <option value="doc_inds">[Doctorado] Indicadores (doc_inds)</option>
				        <option value="doc_tasas">[Doctorado] Tasas (doc_tasas)</option>
				        <option value="doc_recom">[Doctorado] Recomendaciones (doc_recom)</option>
				        <option value="evalprof">[Evaluación del profesorado] (evalprof)</option>
				        <option value="dadespas">[PAS] Encuestas PAS (dadespas)</option>
				        <option value="otros">[Indicadores] Profesorado + Tasas</option>
						<option value="sprodw">[Indicadores] Indicadores</option>
				        <option value="docentia">[Docentia] Evaluación Docentia</option>
				        <option value="enquestes">[SAE/SAEM] Asignaturas para encuestas (enquestes)</option>
				    </select>
				    <div class="uv-table-group-procedure" style="padding-left:20px;padding-top:20px;">
						<span class="btn btn-primary" onclick="run();"><i class="fas fa-clipboard-check"></i> <span th:text="#{data.btn.check}">Comprobar</span></span>
					</div>
				</div>
				<div id="resultsContainer" class="uv-table-group-procedure" style="padding-left:20px;padding-top:20px;cursor:auto;">
					
				</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 type="text/javascript">

	var locale = '[[${#locale.language}]]';
	var orderCol1 = [3, 'asc'], orderCol2 = [1, 'asc'];
	var cursorPosition;
	var numPending;
	var tabParams = {
			paging: true, 
			language:{
				"lengthMenu": "[[#{admin.stats.table.lengthMenu}]]", 
	            "zeroRecords": "[[#{admin.stats.table.zeroRecords}]]",
	            "info": "[[#{admin.stats.table.info}]]",
	            "infoEmpty": "[[#{admin.stats.table.infoEmpty}]]",
	            "infoFiltered": "[[#{admin.stats.table.infoFiltered}]]",
	            "paginate": {
	                "previous": "[[#{admin.stats.table.previous}]]",
	                "next": "[[#{admin.stats.table.next}]]"
	              }
			},
			searching: true,
			order:[orderCol1, orderCol2],
			orderCellsTop: true,
			//fixedHeader: true, // Not compatible with android
			info: false,
			responsive: false,
			initComplete: function () {
				var api = this.api();
	        	this.api()
	        	.columns()
                .eq(0)
                .each(function (colIdx) {
                    var cell = $('.filters th').eq(
                        $(api.column(colIdx).header()).index()
                    );
                    var title = $(cell).text();
                    $(cell).html('<input type="text" placeholder="' + title + '" />');
                    $('input', $('.filters th').eq($(api.column(colIdx).header()).index()))
                        .off('keyup change')
                        .on('change', function (e) {
                            $(this).attr('title', $(this).val());
                            var regexr = '({search})'; 
                            cursorPosition = this.selectionStart;
                            api.column(colIdx)
                               .search(   
                                    this.value != ''
                                        ? regexr.replace('{search}', '(((' + this.value + ')))')	
                                        : '',
                                    this.value != '',
                                    this.value == ''
                                )
                                .draw();
                        })
                        .on('keyup', function (e) {
							e.preventDefault();
                            e.stopPropagation();
                            $(this).trigger('change');
                            $(this)
                                .focus()[0]
                                .setSelectionRange(cursorPosition, cursorPosition);
                        });
                });
    		}
		};
	
		$( document ).ready(function(){ 
			layout = new Layout("");
			layout.initTableLayout({paging:false});
			layout.closeLoadingSpinner(".uv-loading-spinner");
			
		});
		
		function showSpinner(){
			var spinner = `<div class="d-flex justify-content-center">
								<div class="spinner-border text-primary" role="status" style="font-size: 150%; text-align: center; width: 100px; height: 100px;">
									<span class="sr-only">Loading...</span>
								</div>
							</div>
						  `;
			$('#resultsContainer').html(spinner);
		}
		
		function run(){
			showSpinner();
			$.post("/data/count", {enquesta:$('select[name="enquesta"]:enabled').val()})
				.done(function(d){ 
					if(d == 0){
						$('#resultsContainer').html(`[INFO] [[#{data.consolide.nodata}]]`);
					}
					else{
						numPending = d;
						checkDuplicates();
					}
				});
		}
		
		function consolidate(){
			showSpinner();
			$.post("/data/consolidate", {enquesta:$('select[name="enquesta"]:enabled').val()})
				.done(function(d){ 
					if(d == -1){
						$('#resultsContainer').html(`
							<div class="uv-table-group-procedure" style="margin-bottom:50px;cursor:default;">
								<span style="color:red;">[ERROR] </span>
								<span> 
									[[#{data.consolide.err3}]]
								</span>
							</div>`);
					}
					else{
						$('#resultsContainer').html(`
							<div class="uv-table-group-procedure" style="margin-bottom:50px;cursor:default;">
								<span style="color:green;">[INFO] </span><span> [[#{data.consolide.ok}]] </span>
							</div>`);
					}
				});
		}
		
		function checkDuplicates(){
			$.post("/data/check/1", {enquesta:$('select[name="enquesta"]:enabled').val()})
				.done(function(data) {					
					var msgErr = `
						<div class="uv-table-group-procedure" style="margin-bottom:50px;cursor:default;">
							<span style="color:red;">[ERROR] </span>
							<span> 
								[[#{data.consolide.err1}]] <br>
								[[#{data.consolide.count}]]: ${numPending}<br> 
								[[#{data.consolide.tabdesc}]]
							</span>
						</div>
						
						<div>
							<p><strong>[[#{data.consolide.actions.info}]]</strong></p>
							<span class="btn btn-secondary pointer" onclick="fixDuplicationIssues();"><i class="fas fa-cog"></i> [[#{data.consolide.actions.action1}]]</span>
						</div>
						`;
					
					if(data.length > 0){
						drawTable(data, msgErr);	
					}
					else {
						checkIntegrity();
					}
				}
			);
		}
		
		function checkIntegrity(){
			$.post("/data/check/2", {enquesta:$('select[name="enquesta"]:enabled').val()})
				.done(function(data) {
					var msgOk = `
						<div class="uv-table-group-procedure" style="margin-bottom:50px;cursor:default;">
							<span style="color:green;">[INFO] </span>
							<span> [[#{data.consolide.noerr}]].</span>
							<span> [[#{data.consolide.count}]]: ${numPending} </span>
						</div>
						<div class="uv-table-group-procedure" style="padding-left:20px;padding-top:20px;cursor:default;">
							<span class="btn btn-primary" onclick="consolidate();"><i class="fas fa-clone"></i> <span>[[#{data.btn.run}]]</span></span>
						</div>`;
					
					var msgErr = `
						<div class="uv-table-group-procedure" style="margin-bottom:50px;cursor:default;">
							<span style="color:red;">[ERROR] </span>
							<span> 
								[[#{data.consolide.err2}]] <br>
								[[#{data.consolide.count}]]: ${numPending}<br> 
								[[#{data.consolide.tabdesc}]]
							</span>
							<div style="margin-top:10px;">
								<span><strong>[[#{data.consolide.actions.info}]]:</strong></span><br>
								<span class="btn btn-secondary pointer" onclick="fixIntegrityIssues('current')"><i class="fas fa-cog"></i> [[#{data.consolide.actions.action2}]]</span>
								<span class="btn btn-secondary pointer" onclick="fixIntegrityIssues('new')"><i class="fas fa-cog"></i> [[#{data.consolide.actions.action3}]]</span>
							</div>
						</div>
						`;
					
					if(data.length > 0){
						drawTable(data, msgErr);	
					}
					else {
						$('#resultsContainer').html(`
							${msgOk}
						`);
					}
				}
			);
		}
		
		function drawTable(data, msgErr){
			var trs = '';
			data.forEach(function(d){
				trs += `
					<tr>
						<td>${d.curs}</td>
						<td>${d.titulacio == null ? '' : d.titulacio}</td>
						<td>${d.centre == null ? '' : d.centre}</td>
					    <td>${d.ambit}</td>
					    <td>${d.tipus}</td>
					    <td>${d.indicador}</td>
				  	</tr>
			`;});
			
			if(data.length > 0){
				$('#resultsContainer').html(`
						${msgErr}
						<div class="uv-table-group-procedure" style="cursor:default;">
							<table class="table table-striped table-bordered display responsive no-wrap" style="margin-bottom:50px;">
								<thead>
									<tr>
										<th class="uv-table">[[#{data.table.0}]]</th>
										<th class="uv-table">[[#{data.table.1}]]</th>
									  	<th class="uv-table">[[#{data.table.2}]]</th>
									  	<th class="uv-table">[[#{data.table.3}]]</th>
									  	<th class="uv-table">[[#{data.table.4}]]</th>
									  	<th class="uv-table">[[#{data.table.5}]]</th>
									</tr>
								</thead>
								<tbody>
								  ${trs}
								</tbody>
							</table>
						</div>
				`);
			}
			else{
				$('#resultsContainer').html(`
					${msgOk}
				`);
			}
			
			$('.table thead tr').clone(true)
						        .addClass('filters')
						        .appendTo('.table thead');
			
			$('.table').DataTable({
				searching: tabParams.searching, 
				paging: tabParams.paging, 
				orderCellsTop: tabParams.orderCellsTop,
				// fixedHeader: tabParams.fixedHeader,  // Not compatible with Android
				info: tabParams.info,
		        responsive: tabParams.responsive,
		        order: tabParams.order,
		        "language": ((!("language" in tabParams)) ? { "emptyTable": this.emptyMsg } : tabParams.language),
		        initComplete: tabParams.initComplete
			});
		}
		
		function fixIntegrityIssues(deleteFrom){
			$.post("/data/fix/integrity/"+deleteFrom, {enquesta:$('select[name="enquesta"]:enabled').val()})
				.done(function(data) {
					alert("[[#{data.consolide.actions.msg}]]: "+data);
					checkIntegrity();
				}
			);
		}

		function fixDuplicationIssues(){
			$.post("/data/fix/duplication", {enquesta:$('select[name="enquesta"]:enabled').val()})
				.done(function(data) {
					alert("[[#{data.consolide.actions.msg}]]: "+data);
					checkIntegrity();
				}
			);
		}
		
	</script>

</body>

</html>
