const fs = require('fs-extra');

const serviceWorkerPath = './server/public/serviceWorker.js';
const updatedStamp = '//#updated';

module.exports = {
    updateServiceWorker: async () => {
        try {
            let content = await fs.readFile(serviceWorkerPath, 'utf8');
            const newStamp = updatedStamp + new Date().toISOString();
            if (content.indexOf(updatedStamp) === -1) {
                content += '\n' + newStamp;
            } else {
                const prevStamp = content.substring(content.indexOf(updatedStamp), content.length);
                content = content.replace(prevStamp, newStamp);
            }

            await fs.writeFile(serviceWorkerPath, content);
            logger.info('ServiceWorker Date Stamp Updated: ' + newStamp);
        } catch (error) {
            throw new Error('Error on updateServiceWorker: ' + error.message);
        }
    }
};