function myHandler(request, values, options) {
    const startSite = "index.html";

    let responseSite = startSite;
    let lastIndexes = [request.url.lastIndexOf("css/"), request.url.lastIndexOf("js/"), request.url.lastIndexOf("html/"), request.url.lastIndexOf("img/")];
    lastIndexes = lastIndexes.filter(function (elem) {
        return elem > -1;
    });
    let lastIndex = Math.max.apply(null, lastIndexes);

    if (lastIndex > -1) {
        responseSite = request.url.substr(lastIndex);
    }

    return caches.open(cacheName).then(function (cache) {
        return cache.match(urlsToCacheKeys.get(new URL(responseSite, self.location).toString())).then(function (result) {
            if (typeof result === 'undefined') {
                return cache.match(urlsToCacheKeys.get(new URL(startSite, self.location).toString()));
            }
            return result;
        }).catch(function (e) {
            console.warn(e);
            return cache.match(urlsToCacheKeys.get(new URL(startSite, self.location).toString()));
        });
    });
}

module.exports = {
    staticFileGlobs: [
        "!(version)/**/*.!(php)",
        // "!(version)/*.!(php)",
        "*.!(php|htaccess)",
        "/",
    ],
    runtimeCaching: [
        {
            urlPattern: /^https:\/\/((matomo\.silas\.link)|(www\.googletagmanager\.com)|(apis\.google\.com)|(.*\.googleusercontent\.com)|(.*\.google.com)).*$/,
            handler: "networkOnly"
        },
        {
            urlPattern: /^https:\/\/((cdn.jsdelivr.net)).*$/,
            handler: "networkFirst"
        },
        {
            urlPattern: /^.*\/data\/.*$/,
            handler: "networkOnly"
            // handler: "networkFirst"
        },
        {
            urlPattern: /^.*\/cached\/.*$/,
            handler: "networkFirst"
        },
        {
            urlPattern: /^.*\/(version)\/.*$/,
            handler: "cacheFirst"
        },
        {
            urlPattern: /^https:\/\/((www\.codecogs\.com)|(latex\.codecogs\.com)).*$/,
            handler: "networkOnly"
        },
        {
            urlPattern: /^.*$/,
            handler: myHandler
        }],
    maximumFileSizeToCacheInBytes: 14194304
};
