/* global chrome */
'use strict'
var modalDialogCustom = require('../ui/modal-dialog-custom')

module.exports = function (filesProviders) {
  if (typeof chrome === 'undefined' || !chrome || !chrome.storage || !chrome.storage.sync) {
    return
  }

  var obj = {}
  var done = false
  var count = 0

  function check (key) {
    chrome.storage.sync.get(key, function (resp) {
      console.log('comparing to cloud', key, resp)

      function confirmDialog (callback) {
        modalDialogCustom.confirm('', 'Overwrite "' + key + '"? Click Ok to overwrite local file with file from cloud. Cancel will push your local file to the cloud.', () => { callback(true) }, () => { callback(false) })
      }

      if (typeof resp[key] !== 'undefined' && obj[key] !== resp[key]) {
        confirmDialog((result) => {
          if (result) {
            console.log('Overwriting', key)
            filesProviders['browser'].set(key, resp[key])
          }
        })
      } else {
        console.log('add to obj', obj, key)
        filesProviders['browser'].get(key, (error, content) => {
          if (error) {
            console.log(error)
          } else {
            obj[key] = content
          }
        })
      }

      done++
      if (done >= count) {
        chrome.storage.sync.set(obj, function () {
          console.log('updated cloud files with: ', obj, this, arguments)
        })
      }
    })
  }

  for (var y in filesProviders['browser'].list()) {
    console.log('checking', y)
    filesProviders['browser'].get(y, (error, content) => {
      if (error) {
        console.log(error)
      } else {
        obj[y] = content
        count++
        check(y)
      }
    })
  }
}

@@ -1412,22 +1412,8 @@
 %0A%0A  
-for (var y in 
 file
@@ -1438,49 +1438,114 @@
 r'%5D.
-list()) %7B%0A    console.log('checking', y)%0A
+resolve('browser', (error, files) =%3E %7B%0A    if (!error) %7B%0A      Object.keys(files).forEach((path) =%3E %7B%0A    
     
@@ -1574,17 +1574,20 @@
 r'%5D.get(
-y
+path
 , (error
@@ -1604,24 +1604,28 @@
  =%3E %7B%0A      
+    
 if (error) %7B
@@ -1617,32 +1617,36 @@
    if (error) %7B%0A
+    
         console.
@@ -1654,32 +1654,36 @@
 og(error)%0A      
+    
 %7D else %7B%0A       
@@ -1687,13 +1687,20 @@
     
+    
 obj%5B
-y
+path
 %5D = 
@@ -1699,32 +1699,36 @@
 path%5D = content%0A
+    
         count++%0A
@@ -1739,34 +1739,65 @@
     
+    
 check(
-y)%0A      %7D%0A    %7D)%0A  %7D
+path)%0A          %7D%0A        %7D)%0A      %7D)%0A    %7D%0A  %7D)
 %0A%7D%0A

fix chrome cloud sync (use of resolve directory)