/*
 Copyright 2014 Google Inc. All Rights Reserved.
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 http://www.apache.org/licenses/LICENSE-2.0
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

// While overkill for this specific sample in which there is only one cache,
// this is one best practice that can be followed in general to keep track of
// multiple caches used by a given service worker, and keep them all versioned.
// It maps a shorthand identifier for a cache to a specific, versioned cache name.

// Note that since global state is discarded in between service worker restarts, these
// variables will be reinitialized each time the service worker handles an event, and you
// should not attempt to change their values inside an event handler. (Treat them as constants.)

// If at any point you want to force pages that use this service worker to start using a fresh
// cache, then increment the CACHE_VERSION value. It will kick off the service worker update
// flow and the old cache(s) will be purged as part of the activate event handler when the
// updated service worker is activated.
var CACHE_SID = 0;
var CACHE_VER = '';
var isPlayerPage = false;
// var CURRENT_CACHES = {};
// var CURRENT_CACHES = null;

async function progressDownloader(urlOrRequest, port, sid) {
  let url = urlOrRequest;
  let response = await fetch(url);
  if (urlOrRequest instanceof Request) {
    url = urlOrRequest.url;
  }
  let isBin = false;
  if (url.endsWith('.mp4')
    || url.endsWith('.mp3')
    || url.endsWith('.jpg')
    || url.endsWith('.png')){
    isBin = true;
  }

  const reader = response.body.getReader();
  const contentLength = +response.headers.get('Content-Length');
  port.postMessage({
    len: contentLength,
    status: 'init',
    sid
  });
  let receivedLength = 0;
  let mb = 0;
  let timeS = new Date().getTime();
  let timeD = 0;
  let speed = 0;
  let chunks = []; // array of received binary chunks (comprises the body)
  while(true) {
    const {done, value} = await reader.read();
    if (done) {
      break;
    }
    chunks.push(value);
    receivedLength += value.length;
    /*mb += value.length;
    if(mb > 1000 * 1000) {
      timeD = new Date().getTime() - timeS;
      // timeD = timeD /1000;
      speed = mb / timeD;
      mb = 0;
      timeS = new Date().getTime();
    }*/
    // console.log(`Received ${receivedLength} of ${contentLength}`)
    // cb && cb(receivedLength , contentLength)
    port.postMessage({
      loaded: value.length,
      status: 'downloading',
      sid
    });
  }

  if (isBin) {
    return new Blob(chunks);
  } else {
    let chunksAll = new Uint8Array(receivedLength);
    let position = 0;
    for(let chunk of chunks) {
      chunksAll.set(chunk, position);
      position += chunk.length;
    }
    return chunksAll; //new TextDecoder("utf-8").decode(chunksAll);
  }

}
self.addEventListener('install', function(event) {
  event.waitUntil(self.skipWaiting()); // Activate worker immediately
});

self.addEventListener('activate', function(event) {
  event.waitUntil(self.clients.claim({
    includeUncontrolled: true
  }).then(function() {
    // After the activation and claiming is complete, send a message to each of the controlled
    // pages letting it know that it's active.
    // This will trigger navigator.serviceWorker.onmessage in each client.
    return self.clients.matchAll().then(function(clients) {
      return Promise.all(clients.map(function(client) {
        // return client.postMessage('The service worker has activated and ' +
        //   'taken control.');
        return client.postMessage({
          name: 'initOk',
        });

      }));
    });
  })); // Become available to all pages
});
/*
self.addEventListener('activate', function(event) {
  // Delete all caches that aren't named in CURRENT_CACHES.
  // While there is only one cache in this example, the same logic will handle the case where
  // there are multiple versioned caches.
  // var expectedCacheNames = Object.keys(CURRENT_CACHES).map(function(key) {
  //   return CURRENT_CACHES[key];
  // });

  event.waitUntil(
    caches.keys().then(function(cacheNames) {
      // return Promise.all(
      //   cacheNames.map(function(cacheName) {
      //     if (expectedCacheNames.indexOf(cacheName) === -1) {
      //       // If this cache name isn't present in the array of "expected" cache names, then delete it.
      //       console.log('Deleting out of date cache:', cacheName);
      //       return caches.delete(cacheName);
      //     }
      //   })
      // );
    }).then(function() {
      return clients.claim();
    }).then(function() {
      // After the activation and claiming is complete, send a message to each of the controlled
      // pages letting it know that it's active.
      // This will trigger navigator.serviceWorker.onmessage in each client.
      return self.clients.matchAll().then(function(clients) {
        return Promise.all(clients.map(function(client) {
          return client.postMessage('The service worker has activated and ' +
            'taken control.');
        }));
      });
    })
  );
});*/

self.addEventListener('message', function(event) {
  // console.log('Handling message event:', event);
  if (event.data.command === 'remove') {
    if (!event.data.key) {
      return;
    }
    caches.delete(event.data.key)
    /*caches.keys().then(function(cacheNames) {
      console.log('clear', cacheNames);
      // return caches.delete(event.data.ver);
      // CACHE_VER = event.data.newVer;
      // CACHE_SID = event.data.sid;
      if (!event.data.key) {
        return;
      }
      return caches.delete(event.data.key);
      return Promise.all(
        cacheNames.map(function(cacheName) {
          if ( cache_ver === cacheName) {
            // If this cache name isn't present in the array of "expected" cache names, then delete it.
            console.log('Deleting out of date cache:', cacheName);
            // localStorage.removeItem('item-cache-'+event.data.sid);
            // self.clients.matchAll().then(function(clients) {
            //   clients.forEach(function(client) {
            //     client.postMessage({
            //
            //     });
            //   });
            // });
            console.log('delete', cacheName)
            return caches.delete(cacheName);
          }
        })
      );
    })*/
      /*.then(function() {
      return clients.claim();
    })*/
      /*.then(function() {
      // After the activation and claiming is complete, send a message to each of the controlled
      // pages letting it know that it's active.
      // This will trigger navigator.serviceWorker.onmessage in each client.
      return self.clients.matchAll().then(function(clients) {
        return Promise.all(clients.map(function(client) {
          return client.postMessage('The service worker has activated and ' +
            'taken control.');
        }));
      });
    })*/
      .then(function() {
        console.log('delete finished')
      event.ports[0].postMessage({
        error: null
      });
    });
    return;
  }
  if (event.data.command === 'clearAll') {
    event.waitUntil(
      caches.keys().then(function(cacheNames) {
        return Promise.all(
          cacheNames.map(function(cacheName) {
            return caches.delete(cacheName);
          })
        );
      }).then(function() {
        event.ports[0].postMessage({
          error: null
        });
      }).catch(err => {
        event.ports[0].postMessage({
          error: err,
        });
      })
    );
    return;
  }
  if (event.data.command === 'listCachedCoursewares') {
    var cacheData = {}
    // caches.open('item-cache-c965d3a0630911e994fa058136a96bb1-1556518161000').then(r=>{console.log(r.keys().then(items=>console.log(items[0])))})
    caches.keys().then((cacheNames) => {
      cacheNames.map((cacheName) => {
        if (cacheName.indexOf('item-cache') > -1) {
          var size = 0;
          caches.open(cacheName).then((cache) => {
            console.log(cacheName)
            cache.keys().then((requests) => {
              console.log(requests[0])
              for(var req of requests) {
                console.log(req)
                cache.match(req.url).then(resp => {
                  console.log(resp.headers.entries())
                })
              //   cache.match(req.url).then((resp) => {
              //     console.log(req.url, resp.length)
              //     size += parseInt(resp.headers['Content-Length'])
              //   }).catch(err => {
              //     console.log(err)
              //   });
              }
            }).then(() => {
              cacheData.cacheName = size;
            })
          });

        }
      });
    }).then(function(result) {
      // event.ports[0].postMessage({
      //   error: null,
      //   urls: urls
      // });
    });
    return;
  }

  // var key = 'item-cache-' + event.data.sid + '-'+ event.data.ver;
  var key = event.data.key;
  var p = caches.open(key).then(function(cache) {
    // throw {name: 'QuotaExceededError'}
    switch (event.data.command) {
      // This command returns a list of the URLs corresponding to the Request objects
      // that serve as keys for the current cache.
      case 'keys':
        return cache.keys().then(function(requests) {
          var urls = requests.map(function(request) {
            return request.url;
          });

          return urls.sort();
        }).then(function(urls) {
          // event.ports[0] corresponds to the MessagePort that was transferred as part of the controlled page's
          // call to controller.postMessage(). Therefore, event.ports[0].postMessage() will trigger the onmessage
          // handler from the controlled page.
          // It's up to you how to structure the messages that you send back; this is just one example.
          event.ports[0].postMessage({
            error: null,
            urls: urls
          });
        });

      // This command adds a new request/response pair to the cache.
      case 'add':
        // If event.data.url isn't a valid URL, new Request() will throw a TypeError which will be handled
        // by the outer .catch().
        // Hardcode {mode: 'no-cors} since the default for new Requests constructed from strings is to require
        // CORS, and we don't have any way of knowing whether an arbitrary URL that a user entered supports CORS.
        var request = new Request(event.data.url, {mode: 'cors', cache: 'reload'}); //  {mode: 'no-cors'}
        // console.log('start', event.data.url);
        // return fetch(request)
        //   .then(function(res){
        //     return res.arrayBuffer();
        //   })
          const startTime = new Date().getTime();
          let len = 0;
          return progressDownloader(request, event.ports[0], event.data.sid).then((ab) => {
            var cl = ab.size ? ab.size : ab.byteLength;
            len = cl;
            return cache.put(event.data.url, new Response(ab, {
              // url: event.data.url,
              // type: 'cors',
              status: 200,
              statusText: 'OK',
              headers: [
                ['Content-Length', cl+''],
              ]
            }));
          }).then(function(r) {
            event.ports[0].postMessage({
              error: null,
              status: 'finished',
              len: len,
              time: new Date().getTime() - startTime
            });
          });

      // This command removes a request/response pair from the cache (assuming it exists).
      case 'delete':
        return cache.delete(event.data.url).then(function(success) {
          event.ports[0].postMessage({
            error: success ? null : 'Item was not found in the cache.'
          });
        });

      default:
        // This will be handled by the outer .catch().
        throw Error('Unknown command: ' + event.data.command);
    }
  }).catch(function(error) {
    // If the promise rejects, handle it by returning a standardized error message to the controlled page.
    console.log('Message handling failed:', event.data.url, error);
    // if (error.name == 'QuotaExceededError') {
      event.ports[0].postMessage({
        //error: {name: 'QuotaExceededError'}
        error: {name: error.name, message: error.message},
        status: 'error'
      });
    // }
  });

  // Beginning in Chrome 51, event is an ExtendableMessageEvent, which supports
  // the waitUntil() method for extending the lifetime of the event handler
  // until the promise is resolved.
  if ('waitUntil' in event) {
    event.waitUntil(p);
  }

  // Without support for waitUntil(), there's a chance that if the promise chain
  // takes "too long" to execute, the service worker might be automatically
  // stopped before it's complete.
});


self.addEventListener('fetch', function(event) {

  // console.log('Handling fetch event for', event.request.method, event.request.url);
  // if (event.request.method !== 'GET' || !CACHE_SID || !CACHE_VER) {
  //   event.respondWith(function(){
  //     return fetch(request).then(networkResponse => {
  //       return networkResponse;
  //     }).catch(_ => {
  //       console.error('direct Fetching failed:', error);
  //
  //       throw error;
  //     })
  //   });
  //
  //   return;
  // }

  /*if (!CACHE_SID || !CACHE_VER) {
    event.request.mode = 'no-cors';
    return fetch(event.request).then(function(response) {
      // console.log('Response from network is:', response);
      console.log(999)
      return response;
    }).catch(function(error) {
      // This catch() will handle exceptions thrown from the fetch() operation.
      // Note that a HTTP error response (e.g. 404) will NOT trigger an exception.
      // It will return a normal response object that has the appropriate error code set.
      console.error('Fetching failed 9:', error);

      throw error;
    });
  }*/
  // var isNormReq = !CACHE_SID || !CACHE_VER;
  // var key = 'item-cache-' + CACHE_SID + '-'+ CACHE_VER;
  if (event.request.method == 'GET' ) {
    if (event.request.headers.get('range')) {
      var pos =
        Number(/^bytes\=(\d+)\-$/g.exec(event.request.headers.get('range'))[1]);
      // console.log('Range request for', event.request.url,
      //   ', starting position:', pos);
      event.respondWith(
        caches.match(event.request.url, {
          ignoreSearch: true,
          ignoreVary: true
        }).then(function(response) {
          if (response) {
            console.log('Found response in cache:', event.request.url);
            return response.arrayBuffer().then(ab => {
              return new Response(
                ab.slice(pos),
                {
                  status: 206,
                  statusText: 'Partial Content',
                  headers: [
                    ['Content-Length', ab.byteLength+''],
                    ['Content-Range', 'bytes ' + pos + '-' +
                    (ab.byteLength - 1) + '/' + ab.byteLength]]
                });
            });

            // return response;
          }
          // event.request.mode = 'cors';
          // event.request.cache = 'reload';
          var request = new Request(event.request.url,
            {
              method: event.request.method,
              mode: 'cors',
              cache: 'reload',
              headers: event.request.headers
            });
          return fetch(request).then(function(response) {
            console.log('Response from network is:', event.request.url);
            return response;
          })/*.then(res => {
            return res.arrayBuffer();
          }).then(ab => {
            return new Response(
              ab.slice(pos),
              {
                status: 206,
                statusText: 'Partial Content',
                headers: [
                  ['Content-Length', ab.byteLength+''],
                  ['Content-Range', 'bytes ' + pos + '-' +
                  (ab.byteLength - 1) + '/' + (pos + ab.byteLength)]]
              });
          })*/
        })
        /*caches.open(key)
          .then(function(cache) {
            return cache.match(event.request.url);
          }).then(function(res) {
          if (!res) {
            return fetch(event.request)
              .then(res => {
                return res.arrayBuffer();
              });
          }
          return res.arrayBuffer();
        }).then(function(ab) {
          return new Response(
            ab.slice(pos),
            {
              status: 206,
              statusText: 'Partial Content',
              headers: [
                ['Content-Length', ab.byteLength+''],
                ['Content-Range', 'bytes ' + pos + '-' +
                (ab.byteLength - 1) + '/' + ab.byteLength]]
            });
        })*/
      );
    } else {
      // console.log('Non-range request for', event.request.url);
      event.respondWith(
        // caches.match() will look for a cache entry in all of the caches available to the service worker.
        // It's an alternative to first opening a specific named cache and then matching on that.
        caches.match(event.request, {
          ignoreSearch: true,
          ignoreVary: true
        }).then(function(response) {
          if (response) {
            // console.log('%c Response in cache:', 'color:DodgerBlue;', response);
            return response;
          }

          // event.request will always have the proper mode set ('cors, 'no-cors', etc.) so we don't
          // have to hardcode 'no-cors' like we do when fetch()ing in the install handler.
          // event.request.mode = 'cors';
          // cache: 'reload'
          if (event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin') {
            return;
          }
          // console.log('No response found in cache.', event.request.url);
          return fetch(event.request).then(function(response) {
            // console.log('%c Response from network is:', 'color:#bada55', response);

            return response;
          }).catch(function(error) {
            // This catch() will handle exceptions thrown from the fetch() operation.
            // Note that a HTTP error response (e.g. 404) will NOT trigger an exception.
            // It will return a normal response object that has the appropriate error code set.
            console.error('Fetching failed:', error);

            // throw error;
          });
        })
      );
    }
  } else {
    event.respondWith(
      fetch(event.request).then(function(response) {
        // console.log('not get from network:', response);
        // console.log(888)
        return response;
      }).catch(function(error) {
        // This catch() will handle exceptions thrown from the fetch() operation.
        // Note that a HTTP error response (e.g. 404) will NOT trigger an exception.
        // It will return a normal response object that has the appropriate error code set.
        console.error('Fetching failed 8:', error);
        throw error;
      })
    );
  }
});

