import { authenticate, httpTransport } from 'plug-auth-client'

const API_URL = 'https://rs.extplug.com'

export default class Storage {
  constructor ({ url = API_URL } = {}) {
    this.baseUrl = url

    this.token = authenticate({
      transport: httpTransport({ url: `${this.baseUrl}/auth` })
    }).then((result) => result.token)
  }

  getSettings (room) {
    return fetch(`${this.baseUrl}/${room}`)
      .then((response) => response.json())
  }

  getStyles (room) {
    return fetch(`${this.baseUrl}/${room}.css`)
      .then((response) => response.text())
  }
  getStylesSource (room) {
    return fetch(`${this.baseUrl}/${room}.css?source`)
      .then((response) => response.text())
  }

  saveSettings (room, settings) {
    return this.token.then((token) =>
      fetch(`${this.baseUrl}/${room}`, {
        method: 'PUT',
        headers: {
          authorization: `JWT ${token}`,
          accept: 'application/json',
          'content-type': 'application/json'
        },
        body: JSON.stringify(settings)
      })
    ).then((response) => response.json())
  }

  saveStyles (room, cssText) {
    return this.token.then((token) =>
      fetch(`${this.baseUrl}/${room}.css`, {
        method: 'PUT',
        headers: {
          authorization: `JWT ${token}`,
          accept: 'application/json',
          'content-type': 'text/css'
        },
        body: cssText
      })
    ).then((response) => response.json())
  }
}

@@ -99,16 +99,289 @@
 g.com'%0A%0A
+function rejectNonOK(response) %7B%0A  if (response.ok) %7B%0A    return response%0A  %7D%0A  return response.json().catch(() =%3E null).then((json) =%3E %7B%0A    const error = new Error('An unknown error occurred.')%0A    error.body = json%0A    error.response = response%0A    throw error;%0A  %7D)%0A%7D%0A%0A
 export d
@@ -674,16 +674,41 @@
 room%7D%60)%0A
+      .then(rejectNonOK)%0A
       .t
@@ -816,16 +816,41 @@
 %7D.css%60)%0A
+      .then(rejectNonOK)%0A
       .t
@@ -970,16 +970,41 @@
 ource%60)%0A
+      .then(rejectNonOK)%0A
       .t
@@ -1378,32 +1378,64 @@
 )%0A      %7D)%0A    )
+%0A      .then(rejectNonOK)%0A      
 .then((response)
@@ -1774,21 +1774,53 @@
      %7D)%0A
-
     )
+%0A      .then(rejectNonOK)%0A      
 .then((r

Handle error responses from the room settings server.