<% require 'uri' %>
var CACHE_VERSION = 'v16';
var CACHE_NAME = CACHE_VERSION + ':sw-cache-';

function onInstall(event) {

    <% begin  %>
      <% Product.all.each do |product| %>
            try {
                fetch('/product/<%= product.id %>').then(function(response) {
                    caches.open(CACHE_NAME)
                        .then(function(cache) {
                            cache.put('/product/<%= product.id %>', response.clone());
                        });
                });
            }catch (e) {
                console.log(e);
            }
      <% end %>
    <% rescue %>
    <% end %>
    try {
          event.waitUntil(
            caches.open(CACHE_NAME).then(function prefill(cache) {
                return cache.addAll([
                  'https://s3.ap-northeast-2.amazonaws.com/static.channel.io/emoji/v3/emojis.min.json',
                  'https://fonts.googleapis.com/css?family=Noto+Sans:400,700',
                  'https://fonts.googleapis.com/earlyaccess/notosanskr.css'
              ]);
            })
          );
          event.waitUntil(
              caches.keys().then(function(cacheNames) {
                  cacheNames.forEach(function(cacheName) {
                      caches.delete(cacheName);
                  });
              })
          )
    }catch (e) {
        console.log(e);
        console.log("install err catch");
    }
}

function onActivate(event) {
  console.log('[Serviceworker]', "Activating!", event);
    event.waitUntil(
        caches.keys().then(function(cacheNames) {
            return Promise.all(
                cacheNames.filter(function(cacheName) {
                    return cacheName.indexOf(CACHE_VERSION) !== 0;
                }).map(function(cacheName) {
                    return caches.delete(cacheName);
                })
            );
        })
    );
}

// Borrowed from https://github.com/TalAter/UpUp
function onFetch(event) {
    try{
      if(event.request.method != 'GET' ||
          event.request.url.includes('order') ||
          event.request.url.includes('mypage') ||
          event.request.url.includes('users') ||
          event.request.url.includes('admin') ||
          event.request.url.includes('create') ||
          event.request.url.includes('toss') ||
          event.request.url.includes('iamport') ||
          event.request.url.includes('collect') ||
          event.request.url.includes('ga-audiences') ||
          event.request.url.includes('tojung.me/best')
      ){
          return;
      }

//      console.log(event;
      event.respondWith(
        // try to return untouched request from network first

        caches.match(event.request)
                  .then(function (response) {
                      if(response){
                          return response
                      }
                      var fetchRequest = event.request.clone();
                      return fetch(fetchRequest).then(
                        function (response) {
                            // Check if we received a valid response
                            if (!response || response.status == 0) {
                                return response;
                            }
                            // console.log(response.clone())
                            var responseToCache = response.clone();

                            caches.open(CACHE_NAME)
                                .then(function (cache) {
                                    cache.put(event.request.url, responseToCache);
                                });

                            return response;
                        }
                    )
                  })
      )
        event.waitUntil(
            update(event.request)
                .then(refresh)
        )

      event.waitUntil(
          caches.keys().then(function(cacheNames) {
              return Promise.all(
                  cacheNames.filter(function(cacheName) {
                      return cacheName.indexOf(CACHE_VERSION) !== 0;
                  }).map(function(cacheName) {
                      return caches.delete(cacheName);
                  })
              );
          })
      )
    }catch (e) {
        console.log(e);
    }
}

self.addEventListener('install', onInstall);
self.addEventListener('activate', onActivate);
self.addEventListener('fetch', onFetch);

function update(request) {
    return caches.open(CACHE_NAME).then(function (cache) {
        return fetch(request).then(function (response) {
            return cache.put(request, response.clone()).then(function () {
                return response;
            });
        });
    });
}
function refresh(response) {
    return self.clients.matchAll().then(function (clients) {
        clients.forEach(function (client) {

            var message = {
                type: 'refresh',
                url: response.url,
                eTag: response.headers.get('ETag')
            };

            client.postMessage(JSON.stringify(message));
        });
    });
}

self.addEventListener('push', function (event) {
    var jsonbody = JSON.parse(event.data && event.data.text());

    var title = jsonbody.title || "New Blog Post";
    var body = jsonbody.content || "Come to wenghan.me";
    var dir = 'ltr';
    var tag = "push-simple-demo-tag";
    var data = jsonbody.link || "/";
    var icon = "<%= asset_path 'logo.png' %>";
    var renotify = true;
    var actions = [{ action: 'confirm', title: 'Visit', icon: icon }];

    event.waitUntil(self.registration.showNotification(title, { body: body, icon: icon, dir: dir, tag: tag, renotify: renotify, data: data, actions: actions }));
});

self.addEventListener('notificationclick', function (event) {
    var notification = event.notification;
    var action = event.action;
    var link = notification.data;
    if (action === 'confirm') {
        notification.close();
    } else {
        notification.close();
    }

    event.waitUntil(clients.matchAll({
        type: "window"
    }).then(function (clientList) {
        for (var i = 0; i < clientList.length; i++) {
            var client = clientList[i];
            if (client.url == link && 'focus' in client) return client.focus();
        }
        if (clients.openWindow) return clients.openWindow(link);
    }));
});
