var cacheStorageKey = 'vsmart-pwa-3'
var cacheList=[
  '/public/mould/video/common/header.html'
]

function send(data)
{
    self.clients.matchAll()
    .then
    (
        function (clients) 
        {
            if (clients && clients.length) 
            {
                clients.forEach
                (
                    function (client) 
                    {
                        // 发送字符串
                        if(data && data instanceof Object)data=JSON.stringify(data)
                        client.postMessage(data);
                    }
                )
            }
        }
    )
}


self.addEventListener
(
    'message', function (event) 
    {
        send(event.data)
    }
);


self.addEventListener
(
  'install',e =>
  {
    e.waitUntil
    (
      caches.open(cacheStorageKey)
      .then(cache => cache.addAll(cacheList))
      .then(() => self.skipWaiting())
    )
  }
)



self.addEventListener
(
  'fetch',function(e)
  {
    //e.request.headers.get('accept')
    //e.request.method === 'GET'
    e.respondWith
    (
      caches.match(e.request).then
      (
        function(response)
        {
          if(response != null)
          {
            return response
          }
          return requestBackend(e,e.request.url)//执行请求备份操作
          //return fetch(e.request.url)
        }
      )
    )
  }
)

self.addEventListener
(
  'activate',function(e)
  {
    e.waitUntil
    (
      //获取所有cache名称
      caches.keys().then
      (
        cacheNames => 
        {
          return Promise.all
          (
            // 获取所有不同于当前版本名称cache下的内容
            cacheNames.filter
            (
              cacheNames => 
              {
                return cacheNames !== cacheStorageKey
              }
            ).map
            (
              cacheNames => 
              {
                return caches.delete(cacheNames)
              }
            )
          )
        }
      ).then
      (
        () => 
        {
          return self.clients.claim()
        }
      )
    )
  }
)


function requestBackend(event,url)
{ 
  // 请求备份操作
  var url = event.request.clone();
  return fetch(url).then
  (
    function(res)
    {   
        // 请求线上资源
        //if not a valid response send the error
        if(!res || res.status !== 200 || res.type !== 'basic' || !url.url.includes('online'))
        {
            return res;
        }
        var response = res.clone();
        caches.open(cacheStorageKey).then
        (
          function(cache)
          { 
            // 缓存从线上获取的资源
            cache.put(event.request, response);
          }
        );

        return res;
    }
  )
}