'use strict'
/* eslint-env browser, webextensions */
/* global optionDefaults */

function saveOption (name) {
  const element = document.querySelector(`#${name}`)
  if (element) {
    const change = {}
    switch (element.type) {
      case 'text':
      case 'url':
        change[name] = element.value
        break
      case 'checkbox':
        change[name] = element.checked
        break
      default:
        console.log('Unsupported option type: ' + element.type)
    }
    browser.storage.local.set(change)
  }
}

function readOption (name) {
  const element = document.querySelector(`#${name}`)
  if (element) {
    browser.storage.local.get(name)
      .then(storage => {
        if (browser.runtime.lastError) {
          console.log(browser.runtime.lastError)
        } else {
          const oldValue = storage[name]
          switch (element.type) {
            case 'text':
            case 'url':
              element.value = oldValue
              break
            case 'checkbox':
              element.checked = typeof (oldValue) === 'boolean' ? oldValue : false
              break
            default:
              console.log('Unsupported option type: ' + element.type)
          }
          element.onblur = () => saveOption(name) // autosave
        }
      })
  }
}

function readAllOptions () {
  Object.keys(optionDefaults).map(key => readOption(key))
}

// initial load
document.addEventListener('DOMContentLoaded', readAllOptions)

// update on external changes such as browserAction menu
browser.storage.onChanged.addListener(readAllOptions)


@@ -682,117 +682,8 @@
 %3E %7B%0A
-        if (browser.runtime.lastError) %7B%0A          console.log(browser.runtime.lastError)%0A        %7D else %7B%0A  
     
@@ -717,18 +717,16 @@
 e%5Bname%5D%0A
-  
         
@@ -755,26 +755,24 @@
 %7B%0A          
-  
 case 'text':
@@ -768,26 +768,24 @@
 ase 'text':%0A
-  
           ca
@@ -798,34 +798,32 @@
 l':%0A            
-  
 element.value = 
@@ -839,34 +839,30 @@
             
- 
- 
 break%0A
-  
           ca
@@ -872,26 +872,24 @@
 'checkbox':%0A
-  
             
@@ -957,18 +957,16 @@
 : false%0A
-  
         
@@ -981,26 +981,24 @@
 k%0A          
-  
 default:%0A   
@@ -990,26 +990,24 @@
    default:%0A
-  
             
@@ -1066,26 +1066,24 @@
 pe)%0A        
-  
 %7D%0A          
@@ -1072,34 +1072,32 @@
       %7D%0A        
- 
- 
 element.onblur =
@@ -1134,30 +1134,117 @@
 osave%0A      
-  %7D%0A  
+%7D)%0A    .catch(error =%3E %7B%0A      console.error(%60Unable to initialize oprions due to $%7Berror%7D%60)%0A
     %7D)%0A  %7D%0A%7D

replace callback with promise