<!DOCTYPE html>
<html lang="de">
    <head>
        <%- include('partials/head') -%>
        <title>FWmonitor - APP</title>
    </head>

    <body>
        <%- include('partials/header') -%>

        <div class="navbar">
            <button class="material-icons" onclick="goBack();">chevron_left</button>

            <h1>Benutzereinstellungen</h1>
        </div>

        <div class="content">
            <div class="flex_column">
                <div class="list">
                    <div class="item">
                        <span class="left material-icons">notifications_active</span>
                        <span class="text">Terminerinnerungen</span>
                        <label class="switch right">
                            <input
                                class="var_notifications_calendar"
                                type="checkbox"
                                onchange="update_notifications_calendar();"
                            />
                            <span class="slider round"></span>
                        </label>
                    </div>

                    <div class="item">
                        <span class="left material-icons">hide_source</span>
                        <span class="text">Status verbergen</span>
                        <label class="switch right">
                            <input
                                class="var_status_hidden"
                                type="checkbox"
                                onchange="update_status_hidden();"
                            />
                            <span class="slider round"></span>
                        </label>
                    </div>
                </div>

                <div class="list">
                    <div class="item">
                        <span class="left material-icons">notifications_active</span>
                        <span class="text">Telegram</span>
                        <label class="switch right">
                            <input type="checkbox" checked disabled />
                            <span class="slider round"></span>
                        </label>
                    </div>
                </div>

                <div class="list" >
                    <div class="item">
                        <span class="left material-icons">notifications_active</span>
                        <span class="text">App</span>
                        <label class="switch right hidden onpermission">
                            <input
                                class="var_appnotifications"
                                type="checkbox"
                                onchange="update_settings_notifications_app(this.checked)"
                            />
                            <span class="slider round"></span>
                        </label>
                        <span class="right notificationBtn" onclick="notifications_askPermission()"
                            >Erlauben</span
                        >
                    </div>      
                    <div class="list" id="endpoint_list" style="margin: 0;"></div>
                    <template id="template-endpoint">
                        <div class="item" style="flex-wrap: wrap;">
                            <!-- <span class="left material-icons">notifications_active</span> -->
                            <span class="text var_name">Endpunkt</span>
                            <span class="right testBtn" style="background-color: #2196f3; padding: .3em;"
                                >Testen</span
                            >
                            <span class="right deleteBtn" style="background-color: #f37775; padding: .3em;"
                                >Löschen</span
                            >
                        </div>
                    </template>
                </div>
            </div>
        </div>

        <%- include('partials/foot') -%>

        <script>
            // https://itnext.io/an-introduction-to-web-push-notifications-a701783917ce
            const pushServerPublicKey = '<%= vapid_public %>';

            // Laden
            async function load_settings_all() {
                try {
                    const user = (await fetch_get(url_user.replace(':id', user_id), true))[0];
                    console.log('user', user);

                    const var_notifications_calendar = document.querySelector(
                        '.var_notifications_calendar'
                    );
                    const var_status_hidden = document.querySelector('.var_status_hidden');
                    const var_appnotifications = document.querySelector('.var_appnotifications');

                    var_notifications_calendar.checked = user.sendRemembers == 1;
                    var_status_hidden.checked = user.statusHidden == 1;
                    var_appnotifications.checked = user.appNotifications > 0;

                    let endpoints = user.appNotificationsSubscription;
                    if(endpoints != '') endpoints = JSON.parse(endpoints); 
                    else endpoints = [];
                    const target = document.querySelector('#endpoint_list');
                    target.innerHTML = '';

                    for(let i = 0; i < endpoints.length; i++) {
                        const ep = JSON.parse(endpoints[i]).endpoint;
                        const name = ep ? ep.replace('https://', '').split('/')[0] : 'Error';

                        const template = document.querySelector('#template-endpoint');
                        const var_name = template.content.querySelector('.var_name');
                        var_name.innerHTML = name;

                        const clone = document.importNode(template.content.firstElementChild, true);
                        clone.id = 'endpoint_' + i;
                        target.append(clone);

                        if(ep) {
                            clone.querySelector('.testBtn').addEventListener('click', (event) => {
                                test_settings_notifications_app(i);
                            });
                        }
                        clone.querySelector('.deleteBtn').addEventListener('click', (event) => {
                            delete_settings_notifications_app(i);
                        });

                        
                    }
                } catch (error) {
                    console.error('load_settings_all', error);
                    if (error.show) alert('Daten konnten nicht geladen werden.');
                }
            }

            // Speichern
            async function update_notifications_calendar() {
                loaderIn();
                try {
                    const var_notifications_calendar = document.querySelector(
                        '.var_notifications_calendar'
                    ).checked;

                    let response = await fetch_post(
                        url_user_notifications_calendar_update.replace(':id', user_id),
                        { value: var_notifications_calendar }
                    );
                    console.log('update_notifications_calendar', response);
                } catch (error) {
                    console.error('update_notifications_calendar', error);
                    alert('Einstellung konnte nicht gesetzt werden.');
                    load_settings_all();
                }

                loaderOut();
            }

            async function update_status_hidden() {
                loaderIn();
                try {
                    const var_status_hidden = document.querySelector('.var_status_hidden').checked;

                    let response = await fetch_post(
                        url_user_status_hidden_update.replace(':id', user_id),
                        { value: var_status_hidden }
                    );
                    console.log('update_status_hidden', response);
                } catch (error) {
                    console.error('update_status_hidden', error);
                    alert('Einstellung konnte nicht gesetzt werden.');
                    load_settings_all();
                }
                loaderOut();
            }

            async function update_settings_notifications_app(status) {
                loaderIn();
                try {
                    const var_appnotifications = document.querySelector('.var_appnotifications');
                    const subscription = await notifications_createSubscription();

                    const response = await fetch_post(
                        url_user_notifications_app_update.replace(':id', user_id),
                        { value: status ? 5 : 0, subscription: JSON.stringify(subscription) }
                    );
                } catch (error) {
                    alert('Push Notifications konnten nicht aktiviert werden.');
                    console.error('update_settings_notifications_app', error);
                }
                load_settings_all();
                loaderOut();
            }

            async function delete_settings_notifications_app(subscriptionId) {
                loaderIn();
                try {
                    const response = await fetch_post(
                        url_user_notifications_app_delete.replace(':id', user_id),
                        {  subid: subscriptionId }
                    );
                } catch (error) {
                    alert('Push Notifications konnten nicht gelöscht werden.');
                    console.error('delete_settings_notifications_app', error);
                }
                load_settings_all();
                loaderOut();
            }

            async function test_settings_notifications_app(subscriptionId) {
                loaderIn();
                try {
                    const response = await fetch_post(
                        url_user_notifications_app_test.replace(':id', user_id),
                        {  subid: subscriptionId }
                    );
                } catch (error) {
                    alert('Push Notifications konnten nicht getestet werden.');
                    console.error('test_settings_notifications_app', error);
                }
                loaderOut();
            }





            // Hilfsfunktionen
            function isPushNotificationSupported() {
                return (
                    'serviceWorker' in navigator &&
                    'PushManager' in window &&
                    location.protocol === 'https:'
                );
            }

            function notifications_checkPromise() {
                try {
                    Notification.requestPermission().then();
                } catch (e) {
                    return false;
                }

                return true;
            }

            function notifications_handlePermission(permission) {
                const notificationBtn = document.querySelector('.notificationBtn');
                const onpermission = document.querySelector('.onpermission');

                // set the button to shown or hidden, depending on what the user answers
                if (
                    Notification.permission === 'denied' ||
                    Notification.permission === 'default' ||
                    !serviceWorker_registration
                ) {
                    notificationBtn.style.display = 'block';
                    onpermission.classList.add('hidden');

                    if (!serviceWorker_registration) {
                        notificationBtn.innerHTML = 'Fehler';
                    }
                } else {
                    notificationBtn.style.display = 'none';
                    onpermission.classList.remove('hidden');
                }
            }

            function notifications_askPermission() {
                const notificationBtn = document.querySelector('.notificationBtn');

                // Let's check if the browser supports notifications
                if (!isPushNotificationSupported()) {
                    console.log('This browser does not support notifications.');
                    notificationBtn.innerHTML = '----';
                } else {
                    if (notifications_checkPromise()) {
                        Notification.requestPermission().then((permission) => {
                            notifications_handlePermission(permission);
                        });
                    } else {
                        Notification.requestPermission(function (permission) {
                            notifications_handlePermission(permission);
                        });
                    }
                }
            }

            function notifications_checkForPermission() {
                Notification.permission;
                const notificationBtn = document.querySelector('.notificationBtn');

                // Let's check if the browser supports notifications
                if (!isPushNotificationSupported()) {
                    console.log('This browser does not support notifications.');
                    notificationBtn.innerHTML = '<span class="material-icons">extension_off</span>';
                } else {
                    notifications_handlePermission(Notification.permission);
                }
            }

            function notifications_createSubscription() {
                //wait for service worker installation to be ready, and then
                return navigator.serviceWorker.ready.then(function (serviceWorker) {
                    // subscribe and return the subscription
                    return serviceWorker.pushManager
                        .subscribe({
                            userVisibleOnly: true,
                            applicationServerKey: pushServerPublicKey
                        })
                        .then(function (subscription) {
                            console.log('User is subscribed.', subscription);
                            return subscription;
                        });
                });
            }

            // Funktionsaufrufe
            loaderFunction = () => {
                load_settings_all();
                notifications_checkForPermission();
            };
        </script>
    </body>
</html>
