// What must be done: Import the service worker implementation built into the SDK
import '@foxitsoftware/foxit-pdf-sdk-for-web-library/lib/MessageWorker.js';

// The following is an example of functionality required by the application layer

const CACHES_ON_REQUEST = [
    '/',
    '/index.html',
    '/index.js',
    '/lib/PDFViewCtrl.css',
    /\/docs\/.+/,
    /\/lib\/.+/
];

const CACHE_NAME = 'v1';

globalThis.addEventListener('install', (event) => {
    event.waitUntil(
        (async () => {
            const cache = await caches.open(CACHE_NAME);
            
            await cache.addAll(['/', '/index.js']);
            
            // The path list generated by automatically scanning the jr-engine directory under the SDK through webpack configuration
            const engineFilePaths = process.env.ENGINE_FILES
            
            // The maximum number of files to be added to the cache in parallel.
            const maxConcurrentRequests = 5;
            
            const numOfParts = Math.ceil(engineFilePaths.length / maxConcurrentRequests);
            
            const partitionedFilePaths = Array.from({length: numOfParts}, (_, i) => {
                return engineFilePaths.slice(i * maxConcurrentRequests, (i + 1) * maxConcurrentRequests);
            });
            for(const filePathBatch of partitionedFilePaths) {
                await cache.addAll(filePathBatch);
            }
        })()
    );
});

globalThis.addEventListener('fetch', (event) => {
    const url = event.request.url;
    const path = url.replace(location.origin, '').replace(/\?[^?]+/, '');

    // Note: This is a special request path. When the application layer processes the request, it needs to be excluded.
    if (/__foxitwebsdk-syncmsg__/.test(path)) {
        return;
    }
    const needToCache = CACHES_ON_REQUEST.find((it) => {
        if (it instanceof RegExp) {
            return it.test(path);
        }
        return it === path;
    });
    if (needToCache) {
        event.respondWith(
            caches
                .match(event.request, {
                    cacheName: CACHE_NAME,
                })
                .then((response) => {
                    if (response) {
                        return response;
                    }
                    return fetch(event.request.clone()).then((response) => {
                        if (
                            !response ||
                            response.status >= 400 ||
                            response.status === 206
                        ) {
                            return response;
                        }
                        caches.open(CACHE_NAME).then((cache) => {
                            cache.add(event.request);
                        });
                        return response;
                    });
                })
        );
    }
});
