// SPDX-License-Identifier: GPL-3.0-or-later
// myMPD (c) 2018-2026 Juergen Mang <mail@jcgames.de>
// https://github.com/jcorporation/mympd

const CACHE = 'myMPD-cache-v__VERSION__';
const subdir = self.location.pathname.replace('/sw.js', '').replace(/\/$/, '');
const urlsToCache = [
    subdir + '/',
    subdir + '/custom.css',
    subdir + '/custom.js',
    subdir + '/css/combined.css',
    subdir + '/js/combined.js',
    subdir + '/assets/appicon-192.png',
    subdir + '/assets/appicon-512.png',
    subdir + '/assets/coverimage-booklet',
    subdir + '/assets/coverimage-folder',
    subdir + '/assets/coverimage-stream',
    subdir + '/assets/coverimage-notavailable',
    subdir + '/assets/coverimage-mympd',
    subdir + '/assets/coverimage-playlist',
    subdir + '/assets/coverimage-smartpls',
    __I18NASSETS__
    subdir + '/assets/ligatures.json',
    subdir + '/assets/MaterialIcons-Regular.woff2',
    subdir + '/assets/mympd-background-dark.svg',
    subdir + '/assets/mympd-background-light.svg'
];

const ignoreRequests = new RegExp(subdir + '/(' + [
    'api/.*',
    'script-api',
    'serverinfo',
    'ca.crt',
    'ws/.*',
    'stream/.*',
    'albumart.*',
    'tagart.*',
    'folderart.*',
    'playlistart.*',
    'webradio.*',
    'proxy.*',
    'browse/.*'].join('|') + ')$');

self.addEventListener('install', function(event) {
    event.waitUntil(
        caches.open(CACHE).then(function(cache) {
            urlsToCache.map(function(url) {
                return cache.add(url).catch(function (reason) {
                    return console.log('ServiceWorker: ' + String(reason) + ' ' + url);
                });
            });
        })
    );
});

self.addEventListener('fetch', function(event) {
    if (event.request.url.indexOf('https://' + self.location.hostname + '/') !== 0 ||
        ignoreRequests.test(event.request.url))
    {
        return false;
    }
    event.respondWith(
        caches.match(event.request).then(function(response) {
            if (response) {
                return response;
            }
            else {
                return fetch(event.request);
            }
        })
    );
});

self.addEventListener('activate', function(event) {
    event.waitUntil(
        caches.keys().then(function(cacheNames) {
            return Promise.all(
                cacheNames.map(function(cacheName) {
                    if (cacheName !== CACHE) {
                        return caches.delete(cacheName);
                    }
                })
            );
        })
    );
});
