<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="tag" tagdir="/WEB-INF/tags" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

<c:set var="req" value="${pageContext.request}" />
<c:set var="url">${req.requestURL}</c:set>
<c:set var="base" value="${fn:substring(url, 0, fn:length(url) - fn:length(req.requestURI))}${req.contextPath}/" />

<!DOCTYPE html>
<html>

<head>
	<tag:head title="Scan" />
</head>

<body class="grey lighten-3">
    <!-- Header -->
    <header class="navbar-fixed">
        <nav class="red">
            <div class="nav-wrapper">
                <span class="brand-logo center mtop-half hide-on-med-and-down"><img src="../img/logo.png"
                        title="Logo Microfolie" class="responsive-img" style="max-width: 128px;" /></span>
                <span class="brand-logo center hide-on-large-only">Microfolie Lens</span>
                <div class="left mleft-2 hide-on-med-and-down">
                    <span>
                        <h5>Microfolie Lens</h5>
                    </span>
                </div>
            </div>
        </nav>
    </header>
    <div class="mtop-5 hide-on-med-and-down"></div>

    <!-- Main -->
    <main class="container">
    	<div class="row">
			<div class="col s12 center-align">
		    	<h3 id="title">QR Code Scanner</h3>
		    </div>
	    </div>
    	<div class="row white z-depth-1">
    		<div class="col s12">
    			<ul class="tabs">
    				<li class="tab col s6"><a href="#scan" class="active">Scanner</a></li>
    				<li class="tab col s6"><a href="#code" class="active">Code</a></li>
    			</ul>
    		</div>
    		<div id="scan" class="col s12">
		        <div class="row">
		            <div class="col s12 center-align">
		                <video id="qr-preview"></video>
		            </div>
		        </div>
    		</div>
    		<div id="code" class="col s12">
    			<div class="row">
    				<div class="col s12">
    					<div class="row mtop-5">
        					<div class="input-field col s8 offset-s2 m6 offset-m3">
          						<i class="material-icons prefix">person</i>
          						<input id="code-input" type="text">
          						<label for="code-input">Code</label>
          						<span id="code-helper" class="helper-text"></span>
       	 					</div>
        				</div>
        				<div class="row mbot-5">
        					<div class="col s12 center-align">
        						<button id="code-btn" class="waves-effect waves-light btn" disabled>
        							<i class="material-icons left">check</i>Valider
        						</button>
        					</div>
        				</div>
    				</div>
    			</div>
    		</div>
    	</div>
    </main>

    <!-- Popup -->
    <div id="ok-popup" class="modal popup">
        <div class="modal-content" style="overflow: hidden;">
            <div class="row">
                <div class="col offset-m1 m3 s12">
                    <i class="material-icons green-text" style="font-size: 8em;">check_circle</i>
                </div>
                <div class="col m7 s12 mtop-3">
                    <h4 id="ok-text">Success message</h4>
                </div>
            </div>    
        </div>
    </div>
    <div id="err-popup" class="modal popup">
        <div class="modal-content" style="overflow: hidden;">
            <div class="row">
                <div class="col offset-m1 m3 s12">
                    <i class="material-icons red-text" style="font-size: 8em;">error</i>
                </div>
                <div class="col m7 s12 mtop-3">
                    <h4 id="error-text">Error message</h4>
                </div>
            </div>    
        </div>
    </div>
    <!--  Loader  -->
    <tag:loader name="loader" />

    <!-- Script -->
    <tag:script />
    <script type="text/javascript" src="../js/instascan.min.js"></script>
    <script type="text/javascript">
    	function sendCode(code, espace, nom, loader, okPopup, errPopup) {
    		loader.open();
            const result = espace ? espace + "/" + code : code;
            $.ajax({
            	type: "POST",
            	url: "${base}api/badge/" + result,
            	error: () => {
            		$("#error-text").html('Une erreur est survenue');
            		loader.close();
            		errPopup.open();
            	},
            	success: (result) => {
            		loader.close();
            		if (result.success) {
            			$("#ok-text").html(result.data.msg.replace("#ESPACE#", nom));
            			okPopup.open();
            		} else {
            			$("#error-text").html(result.data);
            			errPopup.open();
            		}
            	},
            });
    	}
    
    	$(document).ready(() => {
    		const okPopup = M.Modal.getInstance($('#ok-popup'));
    		const errPopup = M.Modal.getInstance($('#err-popup'));
    		const loader = M.Modal.getInstance($('#loader'));
    		
    		// Lecteur cookie espace
            const espace = getCookie("microfolies.lens.espace");
    		// Si pas de cookie retour sur la page d'accueil
            if (espace === undefined) {
                window.location.href = "${base}";
            }
    		
    		// Recupération du nom reel de l'espace pour le titre
    		loader.open();
    		let nom = espace.capitalize();
    		$.ajax({
                type: "GET",
                url: "${base}api/espace/get/" + espace,
                error: () => {
                	loader.close();
                	$('#title').html(nom);
                },
                success: (result) => {
                	loader.close();
                	nom = result.data.libelle.capitalize();
                	$('#title').html(nom);
                },
            });
            
            // Scanner QRcode
            const scanner = new Instascan.Scanner({ video: document.getElementById('qr-preview') });
            scanner.addListener('scan', function (content) {
            	sendCode(content, espace, nom, loader, okPopup, errPopup);
            });
            Instascan.Camera.getCameras().then(function (cameras) {
                if (cameras.length > 0) {
                    scanner.start(cameras[0]);
                }
                else {
                    console.error('No cameras found.');
                }
            }).catch(err => {
                console.error(err);
            });
            
            // Formulaire
            $('#code-input').on('keyup', function() {
            	const regex = /[A-Za-z0-9]{4}/gm;
            	if (regex.test($(this).val()) && $(this).val().length == 4) {
            		$(this).addClass('valid');
            		$(this).removeClass('invalid');
            		$("#code-btn").attr('disabled', false);
            	} else {
            		$(this).addClass('invalid');
            		$(this).removeClass('valid');
            		$("#code-helper").attr('data-error', 'Code invalide, exemple de code : Az6y');
            		$("#code-btn").attr('disabled', true);
            	}
            });
            $('#code-btn').on('click', () => {
            	sendCode($('#code-input').val(), espace, nom, loader, okPopup, errPopup);
            	$('#code-input').val('');
            });
    	});
    </script>
</body>

</html>