<!-- SCRIPT LOADER -->
<script>
    let car_name = localStorage.getItem('car_name');
    let car_funkname = localStorage.getItem('car_funkname');

    let ws_software = null;
    let ws_lastKeepAlive = new Date();

    const url_alarm_list = '/api/v1/alarm/list?offset=:offset&limit=:limit';
    const url_alarm = '/api/v1/alarm/:id';
    const url_alarm_isalarm = '/api/v1/alarm/isalarm';
    const url_alarm_last = '/api/v1/alarm/last';
    const url_alarm_route = '/api/v1/alarm/route/:id';
    const url_alarm_streetCache = '/api/v1/alarm/streetcache/:id';

    const url_map_forstrettpkt = '/rettPunkte.geojson';
    const url_map_hydranten = '/api/v1/hydrant/:lat/:lng';

    const url_cars_id = '/api/v1/car/:id';


    // Server Verbindungsstatus
    function serverStatus_update(val) {
        if (val) {
            document.querySelector('.var_server_ok')?.classList.remove('hidden');
            document.querySelector('.var_server_error')?.classList.add('hidden');
        } else {
            document.querySelector('.var_server_ok')?.classList.add('hidden');
            document.querySelector('.var_server_error')?.classList.remove('hidden');
        }
    }

    // Websocket Server Verbindung
    async function ws_server_connect() {
        try {
            ws_software = new WebSocket(
                'wss://' +
                    window.location.hostname +
                    (window.location.port ? ':' + window.location.port : '') +
                    '?token=' +
                    getCookie('token')
            );

            let ws_statusInterval = null;
            let ws_keepAliveInterval = null;

            const userrights = await fetch_get('/api/v1/user/rights', true);
            if (DEBUG > 0) console.log('userrights', userrights);

            car_name = userrights.name;
            localStorage.setItem('car_name', car_name);

            if (DEBUG > 0) console.log('Software-connection socket connecting...');

            // Sende Status Datensatz
            let ws_sendStatusInitial = () => {
                ws_software.send(
                    `{
                    "topic": "init",
                    "type":"AutoClient",
                    "name":"Auto - ${car_name}",
                    "info":"Initial",
                    "actions":[
                        {"id":"0"},
                        {"id":"7"},
                        {"id":"8", "key": "Version", "value": "<%= version %> / ${hw_version}"},
                        {"id":"-1", "key": "GPS FIX", "value": "${GPS_hasFIX}"},
                        {"id":"9", "key": "GPS Pos", "value": "${GPS_now.lat}, ${GPS_now.lng}"},
                        {"id":"-2", "key": "Wlan", "value": "${status_connWlan.replace(
                            /\"/g,
                            ''
                        )}"},
                        {"id":"-3", "key": "USB Tethering", "value": "${status_usbtether}"},
                        {"id":"-4", "key": "WS Hardware", "value": "${
                            ws_hardware && ws_stateToText(ws_hardware.readyState)
                        }"}
                ]}`
                );
            };
            let ws_sendStatusUpdate = () => {
                ws_software.send(
                    `{
                    "topic": "update",
                    "info":"Update",
                    "actions":[
                        {"id":"-1", "key": "GPS FIX", "value": "${GPS_hasFIX}"},
                        {"id":"9", "key": "GPS Pos", "value": "${GPS_now.lat}, ${GPS_now.lng}"},
                        {"id":"-2", "key": "Wlan", "value": "${status_connWlan.replace(
                            /\"/g,
                            ''
                        )}"},
                        {"id":"-3", "key": "USB Tethering", "value": "${status_usbtether}"},
                        {"id":"-4", "key": "WS Hardware", "value": "${
                            ws_hardware && ws_stateToText(ws_hardware.readyState)
                        }"}
                        ${hw_updateInProgress ? ',{"id":"-5", "key": "Update", "value": "läuft"}' : ''}
                ]}`
                );
            };

            ws_software.onopen = function () {
                if (DEBUG > 0) console.log('Software-connection socket connected!');

                // Sende Status Datensatz
                ws_sendStatusInitial();

                // Setze Verbindungsstatus auf OK
                serverStatus_update(true);

                // Sende alle 30 sek einen Statusdatensatz
                ws_statusInterval = setInterval(() => {
                    ws_sendStatusUpdate();
                }, 30000);

                // KeepAlive Intervall
                ws_lastKeepAlive = new Date();
                ws_keepAliveInterval = setInterval(() => {
                    if (new Date().getTime() - ws_lastKeepAlive.getTime() > 60000) {
                        if (DEBUG > 0) console.error('Software-connection keep-alive timeout!');
                        serverStatus_update(false);
                        ws_software.close();
                    } else {
                        if (DEBUG > 0) console.log('Software-connection keep-alive OK!');
                    }
                }, 60000);
            };

            ws_software.onmessage = function (e) {
                let socket = ws_software;
                let data = e.data;
                if (DEBUG > 1) console.log('Software-connection socket message:', data);

                data = JSON.parse(data);
                const topic = data.topic;
                const message = data.message;

                // Keep Alive
                if (topic == 'ping') {
                    ws_lastKeepAlive = new Date();
                    socket.send(JSON.stringify({ topic: 'pong', message: message }));
                    serverStatus_update(true);
                    loaderOut();
                }

                // Alarm
                if (topic == 'alarm') {
                    hw_sendDispAktiv();

                    // GPS Statistik für Einsatz zurücksetzen
                    localStorage.setItem('gps.distSum', GPS_dist_sum);
                    localStorage.setItem('gps.altMax', GPS_alt_max);
                    localStorage.setItem('gps.altMin', GPS_alt_min);

                    location.reload();
                }

                if (topic == 'init') {
                    // Sende Status Datensatz
                    ws_sendStatusInitial();
                }

                if (topic == 'action_0') {
                    location.reload();
                }

                if (topic == 'action_7') {
                    loaderIn(undefined, undefined, 'Neustart');
                    hw_sendRestart();
                }

                if (topic == 'action_8') {
                    loaderIn(undefined, undefined, 'Update');
                    hw_sendUpdate();
                }

                if (topic == 'car_status-change') {
                    console.log(car_funkname)
                    if(message.indexOf(car_funkname) != -1) {
                        setFunkStatus( message.slice(-1));                        
                    }
                }
            };

            ws_software.onclose = function (e) {
                if (DEBUG > 0)
                    console.log(
                        'Software-connection socket is closed. Reconnect will be attempted in 15 second.',
                        e.reason
                    );
                serverStatus_update(false);
                clearInterval(ws_statusInterval);
                clearInterval(ws_keepAliveInterval);
                setTimeout(function () {
                    ws_server_connect();
                }, 15000);
            };

            ws_software.onerror = function (err) {
                if (DEBUG > 0)
                    console.error(
                        'Software-connection socket encountered error: ',
                        err.message,
                        'Closing socket'
                    );
                serverStatus_update(false);
                clearInterval(ws_statusInterval);
                clearInterval(ws_keepAliveInterval);
                ws_software.close();
            };
        } catch (error) {
            console.error(error);
            setTimeout(function () {
                ws_server_connect();
            }, 15000);
        }
    }

    // Lade Autodaten
    async function carData_load() {
        try {
            const userrights = await fetch_get('/api/v1/user/rights', true);
            if (DEBUG > 0) console.log('userrights', userrights);

            const car_data = await fetch_get(
                url_cars_id.replace(':id', userrights.userid),
                true
            );
            if (DEBUG > 0) console.log('car_data', car_data);
            localStorage.setItem('car_funkname', car_data.funk_name);
            car_funkname = car_data.funk_name;

            if(car_data.funk_status != -1) {
                setFunkStatus(car_data.funk_status);
                document.querySelector('.var_statusNr').classList.remove('hidden');
                document.querySelector('.statusText').classList.remove('hidden');
            }

        } catch (error) {
            console.error('carData_load', error);
        }
    }

    function setFunkStatus(status) {
        document.querySelector('.var_statusNr').innerHTML = 'Status ' + status;
        document.querySelector('.var_statusNr').innerHTML = 'Status ' + status;
        document.querySelector('.statusPopup').innerHTML = 'Status ' + status;
        if (DEBUG > 0) console.log('Neuer Funkstatus: ' + status);

        document.querySelector('.statusPopup').classList.remove('hidden');
        setTimeout(() => {
            document.querySelector('.statusPopup').classList.add('hidden');                            
        }, 2000);

        let statusText = "";
        if(status == 0) statusText = 'Sprechwunsch dringend';
        if(status == 1) statusText = 'Einsatzbereit Funk';
        if(status == 2) statusText = 'Einsatzbereit Wache';
        if(status == 3) statusText = 'Einsatz übernommen';
        if(status == 4) statusText = 'Am Einsatzort';
        if(status == 5) statusText = 'Sprechwunsch';
        if(status == 6) statusText = 'Nicht einsatzbereit';
        if(status == 'C') statusText = 'Einsatzauftrag erhalten';
        if(status == 'J') statusText = 'Sprechaufforderung';
        if(status == 'F') statusText = 'Über Tel. melden';

        document.querySelector('.statusText').innerHTML = statusText;
    }


</script>
