Source: tests/alarmfax.js

const Pdf = require('../models/core/pdf');
const Operation = require('../models/core/core_operation');

function getDemoOperation() {
    /**
     * SET UP SOME DEMO DATA FOR AN OPERATION
     */
    let operation = new Operation();
    operation.setUUID();
    operation.alarmdate = new Date().toLocaleDateString();
    operation.alarmtime = new Date().toLocaleTimeString();
    operation.community = 'Reichenschwannd';
    operation.district = 'Reichenschwand';
    operation.floor = 'EG';
    operation.gear = 'FL Reichenschwand 60-40-01\nKBI Info\nFF Reichenschwand';
    operation.gkx = 4454576.17;
    operation.gky = 5485861.02;
    operation.ils = 'ILS Nürnberg';
    operation.keywordCategory = 'Tier';
    operation.keywordId = 'T2728';
    operation.keywordName = 'Rettung Kleintier';
    operation.keywordRaw = '#T2728#Tier#Rettung Kleintier';
    operation.lat = 49.5078970024166;
    operation.lon = 11.3713430644129;
    operation.location = 'Reichenschwand - Reichenschwand';
    operation.message = 'In der Nähe des Angler-Weiher ssoll sich eine Ziege in einem Zaun verfangen haben und droht laut MT zu ersticken.';
    operation.object = '';
    operation.operationSourceConnector = 'katsys';
    operation.operationState = 1;
    operation.operationnumber = 'T 5.2 201009 10808';
    operation.section = '';
    operation.street = 'Zum Sportplatz';
    operation.subject = 'THL 1';
    operation.zveis = '24131, 24435, 24070';
    return operation;
}

function getMap(lat, lon, callback) {
    var StaticMaps = require('staticmaps');

    const options = {
        width: 600,
        height: 400,
        tileUrl: 'http://openfiremap.org/hytiles/{z}/{x}/{y}.png',
    };

    const map = new StaticMaps(options);
    /*
    const options = {
        width: 600,
        height: 400,
        //tileUrl: 'http://openfiremap.org/hytiles/{z}/{x}/{y}.png',
        zoomRange: {
            max: 20,
        }
    };
    const map = new StaticMaps(options);
    */
    
    const marker = {
        img: `${__dirname}/marker.png`, // can also be a URL,
        offsetX: 24,
        offsetY: 48,
        width: 48,
        height: 48,
        coord: [lon, lat],
    };
    map.addMarker(marker);
    map.render()
        .then(() => map.image.save('single-marker.png'))
        .then(() => {
            console.log('File saved!');
            callback(true);
        })
        .catch((err) => {
            console.log('Error generating map: ' + err.message);
            callback(false);
        });
}

function mapPngToJpg(filename, callback) {
    const fs = require("fs");
    const pngToJpeg = require('png-to-jpeg');

    let buffer = fs.readFileSync(filename);
    pngToJpeg({ quality: 90 })(buffer)
        .then(output => {
            fs.writeFileSync(filename + '.jpeg', output);
            callback(true);
        })
        .catch((err) => {
            console.log('error converting map from png to jpg: ' + err.message);
            callback(false);
        });
}


function generatePDF(map = null) {
    let pdf = new Pdf(null);
    pdf.initialize();

    // add Header
    pdf.headerLogo = __dirname + '/../public/assets/img/logoPdf.jpg';
    pdf.headerTitle = "ALARMDEPECHE | " + operation.operationnumber.value;
    pdf.addHeader(operation.subject.value + ' | ' + operation.keywordName.value, 0, false);

    // add Organization
    pdf.addTable([250], 0);
    pdf.addTableRow(['Feuerwehr Reichenschwand'], [{ padding: 0, color: 0xff0000 }]);
    pdf.addText('----', { textAlign: 'center', color: 0xffffff });
    pdf.addText('----', { textAlign: 'center', color: 0xffffff });

    // add Keyword
    pdf.addText('EINSATZGRUND', { fontSize: 16, textAlign: 'center', color: 0xff0000 });
    pdf.addTable([540], 1, 7, '0xff0000', 0);
    pdf.addTableRow([operation.subject.value + ' - ' + operation.keywordName.value], [{ fontSize: 20, textAlign: 'center', color: 0xff0000 }]);
    pdf.addText('----', { textAlign: 'center', color: 0xffffff });

    // alarm date and time
    console.log(operation.alarmtimeCalc);
    pdf.addText('ALARMIERUNG', { fontSize: 16, textAlign: 'left', color: 0x000000 });
    pdf.addTable([270, 270], 1, 3, '0xa4a4a7');
    pdf.addTableRow(['Zeitpunkt', operation.alarmtimeCalc.value], [{ backgroundColor: 0xe3e3e3 }, {}]);
    pdf.addTableRow(['Leitstelle', operation.ils.value], [{ backgroundColor: 0xe3e3e3 }, {}]);
    pdf.addText('----', { textAlign: 'center', color: 0xffffff });

    // Location
    pdf.addText('EINSATZORT', { fontSize: 16, textAlign: 'left', color: 0x000000 });
    pdf.addTable([270, 270], 1, 3, '0xa4a4a7');
    pdf.addTableRow(['Straße', operation.street.value], [{ backgroundColor: 0xe3e3e3 }, {}]);
    pdf.addTableRow(['Ort', operation.location.value], [{ backgroundColor: 0xe3e3e3 }, {}]);
    pdf.addTableRow(['Gemeinde', operation.community.value], [{ backgroundColor: 0xe3e3e3 }, {}]);
    pdf.addTableRow(['Objekt', operation.object.value], [{ backgroundColor: 0xe3e3e3 }, {}]);
    pdf.addTableRow(['Abschnitt', operation.section.value], [{ backgroundColor: 0xe3e3e3 }, {}]);

    pdf.addText('----', { textAlign: 'center', color: 0xffffff });

    // DISPATCH Message
    pdf.addText('MITTEILUNG', { fontSize: 16, textAlign: 'left', color: 0x000000 });
    pdf.addTable([540], 1, 7, '0x000000', 0);
    pdf.addTableRow([operation.message.value], [{ textAlign: 'left', color: 0x000000 }]);
    pdf.addText('----', { textAlign: 'center', color: 0xffffff });


    // Gear
    pdf.addText('Alarmierte Einsatzmittel', { fontSize: 16, textAlign: 'left', color: 0x000000 });
    pdf.addTable([540], 1, 2);
    operation.gearCalc.value.forEach(gear => {
        pdf.addTableRow([gear]);
    });

    // Karte
    if (map != null) {
        pdf.doc.pageBreak();
        pdf.addText('KARTE EINSATZORT', { fontSize: 16, textAlign: 'left', color: 0x000000 });
        pdf.addText('----', { textAlign: 'center', color: 0xffffff });
        pdf.addImage('single-marker.png.jpeg', 10, 0, 360, 'left');
        pdf.addText('----', { textAlign: 'center', color: 0xffffff });
    }


    pdf.addFooter();
    pdf.writeDocToFile(__dirname + '/alarmfax.pdf', (successPdf) => {
        console.log('success writing alarmfax: ' + successPdf);
    })
}


/**
 * NOW START CREATING THE PDF DOCUMENT
 */

let operation = getDemoOperation();
getMap(operation.lat.value, operation.lon.value, (successMap) => {
    mapPngToJpg('single-marker.png', (successConvert) => {
        if (successConvert) {
            console.log('found map, generating pdf with map');
            generatePDF('single-marker.png.jpeg');
        } else {
            console.log('no map -> only pdf');
            generatePDF();
        }
    })
});