var staticCacheName = "pwa-v" + new Date().getTime();
var filesToCache = [
    '/',
    '/offline',
    '/css/app.css',
    '/js/app.js',
    '/images/icons/icon-72x72.png',
    '/images/icons/icon-96x96.png',
    '/images/icons/icon-128x128.png',
    '/images/icons/icon-144x144.png',
    '/images/icons/icon-152x152.png',
    '/images/icons/icon-192x192.png',
    '/images/icons/icon-384x384.png',
    '/images/icons/icon-512x512.png',
    'https://maxcdn.bootstrapcdn.com/bootswatch/3.3.5/cyborg/bootstrap.min.css',
    'https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css',
    '/assets/theme/css/style.css',
    '/admin/css/main.css',
    '/admin/js/main.js',
    'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js',
    'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js',
    '/assets/mobirise/js/jquery.matchHeight-min.js',
    '/js/main.js',
    '/js/detalle.js',
    '/fotos/tu-marca.jpg',
    '/fotos/Alitas a la BBQ.jpg',
    '/fotos/Bebidas.jpg',
    '/fotos/Burritos.jpg',
    '/fotos/Coca-Cola.jpg',
    '/fotos/Corona.jpg',
    '/fotos/Fanta.jpg',
    '/fotos/Hamburguesa de pollo.jpg',
    '/fotos/Hamburguesa hawaiana.jpg',
    '/fotos/Hamburguesa sencilla.jpg',
    '/fotos/Hamburguesas.jpg',
    '/fotos/Hawaiana.jpg',
    '/fotos/Mexicana.jpg',
    '/fotos/Modelo Especial.jpg',
    '/fotos/Pepsi.jpg',
    '/fotos/Pizzas.jpg',
    '/fotos/Sincronizadas.jpg',
    '/fotos/sol.jpg',
    '/fotos/Tecate.jpg',
    '/fotos/Variedad.jpg',
    '/fotos/Varios.jpg'
];

// Cache on install
// Descargar assets; crea un cache
self.addEventListener("install", event => {
    this.skipWaiting();
    event.waitUntil(
        caches.open(staticCacheName)
            .then(cache => {
                return cache.addAll(filesToCache);
            })
    )
});

/// Clear cache on activate
//cuando el SW toma el control de la aplicación; borrar cache viejo
self.addEventListener('activate', event => {
    event.waitUntil(
        caches.keys().then(cacheNames => {
            return Promise.all(
                cacheNames
                    .filter(cacheName => (cacheName.startsWith("pwa-")))
                    .filter(cacheName => (cacheName !== staticCacheName))
                    .map(cacheName => caches.delete(cacheName))
            );
        })
    );
});

// Serve from Cache
// Manejo de peticiones HTTP; aplicar estrategias del cache
self.addEventListener("fetch", event => {
    event.respondWith(
        caches.match(event.request)
            .then(response => {
                return response || fetch(event.request);
            })
            .catch(() => {
                return caches.match('offline');
            })
    )
});

//sync: recuperamos la conexión a internet

//push: maneja las push notifications
