<script src="{{asset('qz-laravel/app.js')}}"></script>

<script>
    var qzConfig = {};

    function printFromData(data, printer) {
        connectQz()
        .then( () => findPrinter(printer))
        .then( (config) => qz.print(config, data))
        .catch((err) => console.error(err));
    }

    function printFromUrl(url, printer) {
        fetch(url).then((response) => response.json())
        .then((data) => printFromData(data, printer));
    }

    function connectQz(){
        return new Promise((resolve, reject) => {
            if (!qz.websocket.isActive()) {
                qz.websocket.connect().then(resolve, reject);
            }else{
                resolve();
            }
        });    
    }

    function findPrinter(printerName){
        
        return new Promise((resolve, reject) => {
            
            if(qzConfig[printerName] != undefined){
                resolve(qzConfig[printerName]);
            }
            
            qz.printers.find(printerName)
            .then((found) => {
                
                return qz.configs.create(found, { encoding: 'Cp850' });
            })
            .then((config) => {
                qzConfig[printerName] = config;    
                resolve(qzConfig[printerName]);
            })
            .catch(reject);
        });
    }

    
    $( document ).ready(function() {
        qz.security.setCertificatePromise(function(resolve, reject) {
            $.ajax("{{ route('qz.certificate') }}").then(resolve, reject);
        });
        
        qz.security.setSignatureAlgorithm("SHA1"); // Since 2.1
        qz.security.setSignaturePromise(function(toSign) {
            return function(resolve, reject) {
                data = {
                    "_token": "{{ csrf_token() }}",
                    "dataToSign": toSign
                }
                $.post("{{ route('qz.sign') }}", data).then(resolve, reject);
            };
        });
    });
</script>