var apiURL = 'https://api.put.io/v2'
var appURL = 'https://app.put.io'
var storageKey = 'putio-webextension'

browser
  .storage.local.get()
  .then((storage) => {
    var extensionStorage = storage.storageKey

    if (!extensionStorage || !extensionStorage.token) {
      authorize()
    }
  })

function authorize() {
  var redirectURL = browser.identity.getRedirectURL()
  var clientID = '2939'

  var authURL = apiURL + '/oauth2/authenticate'

  authURL += ('?client_id=' + clientID)
  authURL += ('&response_type=token')
  authURL += ('&redirect_uri=' + encodeURIComponent(redirectURL))

  return browser.identity.launchWebAuthFlow({
    interactive: true,
    url: authURL,
  }, validate)
}

function validate(redirectURL) {
  var token = redirectURL.split('#access_token=')[1]

  browser
    .storage.local.set({
      [storageKey]: { token: token },
    })
    .then(() => initialize(token))
}

function initialize(token) {
  var notificationIcon = browser.extension.getURL('icon-notify.png')

  function checkTransferStatus(transfer) {
    console.log(transfer)

    var url = apiURL + '/transfers/' + transfer.id

    var xhr = new XMLHttpRequest()

    xhr.open('GET', url, true)
    xhr.setRequestHeader('authorization', 'token ' + token)

    xhr.onload = function () {
      if (xhr.readyState == 4) {
        const response = JSON.parse(xhr.responseText)

        if (response.transfer.file_id) {
          browser.notifications.create('transfer-finished-' + response.transfer.id + '-' + response.transfer.file_id, {
            type: 'basic',
            iconUrl: notificationIcon,
            title: 'Transfer Finished!',
            message: response.transfer.name + ' is downloaded!',
            buttons: [
              {
                title: 'Go To File',
              }
            ],
          })
        } else {
          setTimeout(checkTransferStatus.bind(null, response.transfer), 10000)
        }
      }
    }

    xhr.send(null)
  }

  function onDownload(info, tab) {
    var url = apiURL + '/transfers/add'

    var data = JSON.stringify({
      url: info.linkUrl,
    })

    var xhr = new XMLHttpRequest()

    xhr.open('POST', url, true)
    xhr.setRequestHeader('Content-type','application/json; charset=utf-8')
    xhr.setRequestHeader('authorization', 'token ' + token)

    xhr.onload = function () {
      if (xhr.readyState == 4) {
        const response = JSON.parse(xhr.responseText)

        browser.notifications.create('transfer-start-success-' + response.transfer.id, {
          type: 'basic',
          iconUrl: notificationIcon,
          title: 'Transfer Started!',
          message: 'We will let you know when ' + response.transfer.name + ' is downloaded!',
        })

        setTimeout(checkTransferStatus.bind(null, response.transfer), 3000)
      } else {
        const response = JSON.parse(xhr.responseText)

        browser.notifications.create('transfer-start-failure', {
          type: 'basic',
          iconUrl: notificationIcon,
          title: 'Oops!',
          message: 'We are unable to download that :/',
        })
      }
    }

    xhr.send(data)
  }

  browser.contextMenus.create({
    title: browser.i18n.getMessage('downloadMenuItem'),
    contexts: ['link'],
    onclick: onDownload,
  })

  browser.notifications.onClicked.addListener(function(notificationId) {
    browser.notifications.clear(notificationId)
  })

  browser.notifications.onButtonClicked.addListener(function(notificationId) {
    var transferId = notificationId.split('-')[2]
    var fileId = notificationId.split('-')[3]
    var url = appURL + '/files/' + fileId

    browser.notifications.clear('transfer-start-success-' + transferId)
    browser.notifications.clear(notificationId)

    browser.tabs.create({
      active: true,
      url: url,
    })
  })
}


@@ -101,16 +101,83 @@
 tension'
+%0Avar notificationIcon = browser.extension.getURL('icon-notify.png')
 %0A%0Abrowse
@@ -258,17 +258,17 @@
  storage
-.
+%5B
 storageK
@@ -269,16 +269,17 @@
 orageKey
+%5D
 %0A%0A    if
@@ -346,16 +346,70 @@
 orize()%0A
+    %7D else %7B%0A      initialize(extensionStorage.token)%0A
     %7D%0A  
@@ -902,24 +902,282 @@
 )%5B1%5D%0A%0A  
-browser%0A
+if (token) %7B%0A    browser.notifications.create('validate-success', %7B%0A      type: 'basic',%0A      iconUrl: notificationIcon,%0A      title: 'Welcome!',%0A      message: 'You can use the right click menu for downloading items to your put.io account!',%0A    %7D)%0A%0A    browser%0A  
     .sto
@@ -1193,16 +1193,18 @@
 l.set(%7B%0A
+  
       %5Bs
@@ -1237,23 +1237,27 @@
  %7D,%0A    
+  
 %7D)%0A    
+ 
+ 
 .then(()
@@ -1279,16 +1279,20 @@
 token))%0A
+  %7D%0A
 %7D%0A%0Afunct
@@ -1319,78 +1319,8 @@
 ) %7B%0A
-  var notificationIcon = browser.extension.getURL('icon-notify.png')%0A%0A
   fu
@@ -1362,35 +1362,8 @@
 ) %7B%0A
-    console.log(transfer)%0A%0A
     

update initial flow