<style scoped>
* {
  box-sizing: border-box;
}
body {
  margin: 0px !important;
  padding: 8px;
  width: 100%;
  height: 100%;
}
.document-wrapper {
  width: 100%;
}
.document-progress {
  width: 100%;
  background-color: #faf9f8;
}
.document-bar {
  height: 30px;
  background-color: #d1e9f2;
  width: 0%;;
  text-align: center;
  line-height: 30px;
  color: #333333;
}
</style>

<div class="document-wrapper">
  <button class="start">Starta</button>
  <div class="document-progress">
    <div class="document-bar">0%</div>
  </div>
  <h2>Dokument utan koppling till sida</h2>
  <div class="document-list"></div>
</div>

<script>

/*(function($) {
  var config = JSON.parse('${configString}');
  var documents = JSON.parse('${documentsString}');
  var url = config.url + '${asdf}';
  $.ajax({
    url: url,
    type: 'GET',
    context: { sessionId: config.sessionId }
  });
})(jQuery);*/
/* 
Split an array into chunks and return an array
of these chunks.
This will *not* preserve array keys.
*/
Array.prototype.chunk = function(groupsize) {
  var sets = [], chunks, i = 0;
  chunks = this.length / groupsize;

  while(i < chunks){
    sets[i] = this.splice(0,groupsize);
    i++;
  }

  return sets;
};

(function($) {
  $(document).ready(function() {
    var config = JSON.parse('${configString}');
    var folder = JSON.parse('${folderString}');
    var current = 0;

    var bar = $('.document-bar');
    var documentList = $('.document-list');
    var progress = function(current) {
      current = current;
      bar.width(current + '%');
      bar.html(Math.round(current) + '%');
    };

    var printDocuments = function(folder, documents) {
      if (documents.length <= 0) {
        return;
      }
      console.log('folder:', folder);
      var folderId = folder.id.replace('.', '_');
      var folderElement = $('#' + folderId);
      if (!folderElement.length) {
        folderElement = $( '<div id="' + folderId + '"></div>').appendTo(documentList);
      }
      var html = '';
      html += '<div>';
      html +=   '<span>Mapp: </span><a href="' + folder.editUrl + '">' + folder.name + '</a>';
      html +=   '<ul>';
      documents.forEach(function(document) {
        html +=   '<li>';
        html +=     '<a href="' + document.editUrl + '">' + document.name + '</a>';
        html +=   '</li>';
      });
      html +=   '</ul>';
      html += '</div>';
      folderElement.append(html);
      
      /*documents.forEach(function(document) {
        documentList.append
      });*/
    };

    var createUrl = function(folder) {
      var ids = folder.documents.map(function(document) {
        return document.id;
      });
      return config.endpoint + folder.id + '/' + folder.id + '/referencesCheck?ids%5B%5D=' + ids.join('&ids%5B%5D=');
    };

    var handleReference = function(folder, documents) {
      function compare(otherArray) {
        return function(current) {
          return otherArray.filter(function(other) {
            return other.nodeId == current.id
          }).length == 0;
        }
      }
      return folder.documents.filter(compare(documents));
      //console.log('In:', folder.name, 'found:' , result.length, ':', result);
      //folder.documents
    };

    var referencesCheck = function(folder, url) {
      $.getJSON({
          url: url,
          type: 'GET',
          context: { sessionId: config.sessionId }
        })
        .done(function(data) {
          //console.log('Current:', current, 'folderLength: ', folder.documents.length, 'asdf', config.documentCount);

          //console.log('Data:', data);
          current += folder.documents.length;
          progress((current / config.documentCount) * 100);

          // Handle reference
          //var withoutReference = handleReference(folder, data);
          printDocuments(folder, handleReference(folder, data));
          

          folder.children.forEach(function(child) {
            checkReferences(child);
          });

          /*if (current >= folder.documents.length) {
            console.log('Done:', folder.name);
          }*/
        })
        .fail(function(jqxhr, textStatus, error) {
          console.log('Error:', textStatus, error);
        });
    };

    var checkReferences = function(folder) {
      console.log('checkReferences:', folder.name, folder.documents.length);

      if (folder.documents.length > 100) {
        var documentsChunks = folder.documents.chunk(100);
        documentsChunks.forEach(function(documentsChunk, index) {
          var folderChunk = {
            id: folder.id,
            name: folder.name,
            editUrl: folder.editUrl,
            documents: documentsChunk,
            children: []
          };
          if (index === documentsChunks.length - 1) {
            folderChunk.children = folder.children;
          }
          referencesCheck(folderChunk, createUrl(folderChunk));
        });
      } else if (folder.documents.length > 0) {
        referencesCheck(folder, createUrl(folder));
      } else {
        folder.children.forEach(function(child) {
          checkReferences(child);
        });
      }

      
    };

    $('.start').click(function(event) {
      $('.start').prop('disabled', true);
      progress(0);
      current = 0;
      documentList.empty();
      checkReferences(folder);
      //update(config.start, config.limit);
    });
  });
})(jQuery);

</script>
