angular.module('utils.packetHandlers', ['utils.webRTC', 'utils.fileUpload', 'utils.linkGeneration'])


.factory('packetHandlers', ['webRTC', 'fileUpload', 'linkGeneration', 'fileTransfer', '$q', function(webRTC, fileUpload, linkGeneration, fileTransfer, $q) {
  var packetHandlerObj = {};
  var chunkCount = 0;
  var fullArray = [];
  packetHandlerObj.accepted = function(data, conn, scope) {
    var fileKey = linkGeneration.fuid();

    fileTransfer.myItems.forEach(function(val) {
      if (val.name === data.name && val.size === data.size) {
        webRTC.sendDataInChunks(conn, {
          file: val,
          name: data.name,
          size: data.size,
          id: fileKey,
          scopeRef: scope
        });
      }
    });
  };

  packetHandlerObj.offer = function(data, conn, scope) {
    scope.$apply(function() {
      var index = fileTransfer.offers.length;
      fileTransfer.offers.push({
        name: data.name,
        size: fileUpload.convert(data.size),
        accept: function() {
          conn.send({
            name: data.name,
            size: data.size,
            type: 'file-accepted'
          });
          fileTransfer.offers.splice(index, 1);
        }
      });
    });
  };

  packetHandlerObj.chunk = function(data, scope) {
    if (data.count === 0) {
      scope.$apply(function() {
        fileTransfer.activeFileTransfers[data.id] = {
          buffer: [],
          id: data.id,
          name: data.name,
          size: data.size,
          progress: 0
        };
      });
    }
    var transferObj = fileTransfer.activeFileTransfers[data.id];
    transferObj.buffer.push(data.chunk);
    scope.$apply(function() {
      transferObj.progress += 16348;
    });
    // this code takes the data off browser memory and stores to user's temp storage every 5000 packets.
    if (transferObj.buffer.length >= 5000) {
      // console.log('saved chunk at', transferObj.buffer.length);
      var blobChunk = new Blob(transferObj.buffer);
      transferObj.buffer = [];
      localforage.setItem(chunkCount.toString(), blobChunk);
      chunkCount++;
    }

    if (data.last) {
      var lastBlob = new Blob(transferObj.buffer);
      transferObj.buffer = [];
      localforage.setItem(chunkCount.toString(), lastBlob, function() {
          console.log('saved last chunk');
        })
        .then(
          function(result) {
            // console.log('first promise resolved');
            chunkCount++;
            localforage.iterate(function(value, key, iterationNumber) {
                fullArray[key] = value;
              }, function(err) {
                if (!err) {
                  console.log('Iteration has completed');
                }
              })
              .then(function() {
                // console.log('all promise resolved');
                var newFile = fileUpload.convertFromBinary({
                  file: new Blob(fullArray),
                  name: transferObj.name,
                  size: transferObj.size
                });
                fullArray = [];
                localforage.clear(function(err) {
                  console.log('local db cleared');
                });
                fileTransfer.finishedTransfers.push(newFile);
                var downloadAnchor = document.getElementById('fileLink');
                downloadAnchor.download = newFile.name;
                downloadAnchor.href = newFile.href;
              });
          }
        );
    }
  };

  return packetHandlerObj;

}]);

@@ -1857,27 +1857,24 @@
 000) %7B%0A     
- //
  console.log
@@ -1920,16 +1920,16 @@
 ength);%0A
+
       va
@@ -2021,32 +2021,42 @@
 lforage.setItem(
+data.id + 
 chunkCount.toStr
@@ -2230,16 +2230,26 @@
 setItem(
+data.id + 
 chunkCou
@@ -2556,31 +2556,374 @@
     
-fullArray%5Bkey%5D = value;
+if (key.startsWith(data.id)) %7B%0A                  fullArray%5Bkey%5Bdata.id.length%5D%5D = value;%0A                  // delete doucment after appending%0A                  localforage.removeItem(data.id + (iterationNumber - 1));%0A                  console.log('Removed key:', data.id + (iterationNumber - 1))%0A                %7D%0A                // clear this document from db after
 %0A   
@@ -3407,128 +3407,8 @@
 %5B%5D;%0A
-                localforage.clear(function(err) %7B%0A                  console.log('local db cleared');%0A                %7D);
 %0A   

Add ability to receieve multiple files with no db conflicts in packetHandlersFactory.js