// Import Workbox (https://developers.google.com/web/tools/workbox/)


var SWInterval = {};

importScripts('/synclib.js');
self.__WB_MANIFEST = PrecacheStaticURLs;


importScripts('/dist/js/workbox-sw.js');



const { precacheAndRoute, registerRoute } = workbox.routing;
const { StaleWhileRevalidate, CacheFirst, NetworkFirst } = workbox.strategies;
const { BackgroundSyncPlugin } = workbox.backgroundSync;

// Precaching static assets
workbox.precaching.precacheAndRoute(self.__WB_MANIFEST || []);




const urlsToCache = PrecacheStaleRevalidateURLs;

registerRoute(
  ({ request }) => {
    return urlsToCache.includes(new URL(request.url).pathname);
  },
  new StaleWhileRevalidate({
    cacheName: 'page-stale-while-revalidate-cache', // Name of the cache
    plugins: [

    ],
  })
);

function fetchStaleWhileRevalidate(NewurlsToCache){
  registerRoute(
    ({ request }) => {
      return NewurlsToCache.includes(new URL(request.url).pathname);
    },
    new StaleWhileRevalidate({
      cacheName: 'new-page-stale-while-revalidate-cache', 
      plugins: [
  
      ],
    })
  );
}


  // registerRoute(
  //   ({ url }) => url.pathname.startsWith('/RequestData/File/'),
  //   new CacheFirst({
  //     cacheName: 'request-data-cache',
  //     plugins: [
  //       {
  //         cacheableResponse: {
  //           statuses: [0, 200], // Cache responses with status 0 or 200
  //         },
  //       },
  //       {
  //         expiration: {
  //           maxAgeSeconds: 30 * 24 * 60 * 60, // Cache for 30 days
  //           maxEntries: 2000, // Limit to 2000 entries
  //         },
  //       },
  //     ],
  //   })
  // );


  // workbox.routing.registerRoute(
  //   ({ url }) => url.pathname.startsWith('/RequestData/File/'),
  //   new workbox.strategies.CacheFirst({
  //     cacheName: 'request-data-cache',
  //     plugins: [
  //       new workbox.cacheableResponse.CacheableResponsePlugin({
  //         statuses: [0, 200],
  //       }),
  //       new workbox.expiration.ExpirationPlugin({
  //         maxAgeSeconds: 30 * 24 * 60 * 60, // 30 days
  //         maxEntries: 2000,
  //       }),
  //     ],
  //   })
  // );



workbox.routing.registerRoute(
   ({ url }) => {
    console.log('Checking URL:', url.href);
    return url.pathname.startsWith('/RequestData/File/');
  },
  async ({ request }) => {
    console.log('Fetching:', request.url);

    const cache = await caches.open('request-data-cache');
    const cachedResponse = await cache.match(request);
    if (cachedResponse) {
      console.log('Serving from cache:', request.url);
      return cachedResponse;
    }

    console.log('Network request:', request.url);
    const response = await fetch(request);

    // Clone the response before caching
    if (response && response.status === 200) {
      cache.put(request, response.clone());
      console.log('Stored in cache:', request.url);
    }

    return response;
  }
);


  // workbox.routing.registerRoute(
  //   ({ url }) => url.pathname.startsWith('/RequestData/File/'),
  //   async ({ request }) => {
  //     console.log('Fetching:', request.url); 
  //     const cache = await caches.open('request-data-cache');
  //     const response = await cache.match(request);
  //     if (response) {
  //       console.log('Serving from cache:', request.url); // Log if served from cache
  //       return response;
  //     }
  //     console.log('Network request:', request.url); // Log network request
  //     return fetch(request);
  //   }
  // );



self.addEventListener('install', event => {
  console.log('Service Worker installed');
  self.skipWaiting();
});

self.addEventListener('activate', event => {
  console.log('Service Worker activated');
  event.waitUntil(
    self.clients.claim()
  );
});




function PostMessage(objecttosend) {
  self.clients.matchAll().then(clients => {
    if (clients.length === 0) {
      //  console.log('No clients found to send messages.');
    }
    clients.forEach(client => {
      //  console.log('Sending message to client:', client);
      client.postMessage(objecttosend);
    });
  }).catch(error => {
    // console.error('Error fetching clients:', error);
  });
}

/*
async function fetchDataAndProcess(url, callback = null, method = 'GET', data = null, log = false) {
  if (log) {console.log('Trying to fetch', url, callback, 'method', method, 'data', data);  }
  if(!navigator.onLine){return false;}
  try {
    const options = {
      method: method,
      headers: {
        'Content-Type': 'application/json'
      }
    };

    if (data && (method === 'POST' || method === 'PUT')) {
      try {
        options.body = JSON.stringify(data);
      } catch (error) {
        options.body = data; 
      }
    }
    const response = await fetch(url, options);
    if (!response.ok) {
      throw new Error('Network response was not ok: ' + response.statusText);
    }
    const responseClone = response.clone(); 
    let responseData;
    try {
      responseData = await responseClone.json();
    } catch (error) {
      responseData = await response.text();
    }

    if (callback && typeof callback === 'function') {
      if (log) {
        console.log('Running callback');
      }
      callback(responseData);
    }
  } catch (error) {
    if(log){
      console.log('There has been a problem with your fetch operation: ', url, error);
    }
    
  }
}


function FetchDataAndPostInterval(url,type,interval){
  if (!url || !type || !interval){return false;}
  if (SWInterval[type]) {
    console.warn(`Interval for type "${type}" is already set. Aborting.`);
    return;
  }
  function sendPostCode(response){
    PostMessage({type:type,'data':response});
  }

  SWInterval[type] = setInterval(() => fetchDataAndProcess(getFullURL(url), sendPostCode), interval);
}

function checkIfHostIsOnline() {
  // Get the current host from window.location
  const host = window.location.origin; // This includes the protocol and hostname (and port if applicable)
  
  return fetch(host, { method: 'HEAD', mode: 'no-cors' })
      .then(() => true) // If the fetch is successful, return true
      .catch(() => false); // If there's an error, return false
}
  */



function INIT() {
  //FetchDataAndPostInterval('/get/isloggedin', 'loggedin', 10000);
  //FetchDataAndPostInterval('/get/isExec', 'exec', 10000);
}

self.addEventListener('message', event => {
  if (event.data.type == 'INIT') {
    //INIT();


  }
});


