/* global cozy */

import { LocalStorage as Storage } from 'cozy-client-js'

const getStorage = () => new Storage()
const getClientName = device => `Cozy Files Application on ${device} (${Math.random().toString(36).slice(2)})`

const getClientParams = (device) => ({
  redirectURI: 'http://localhost',
  softwareID: 'io.cozy.mobile.files',
  clientName: getClientName(device),
  scopes: ['io.cozy.files']
})

const getAuth = (onRegister, device) => ({
  storage: getStorage(),
  clientParams: getClientParams(device),
  onRegistered: onRegister
})

export const initClient = (url, onRegister = null, device = 'Device') => {
  console.log(`Cozy Client initializes a connection with ${url}`)
  cozy.client.init({
    cozyURL: url,
    offline: {doctypes: ['io.cozy.files']},
    oauth: getAuth(onRegister, device)
  })
}

export const initBar = () => {
  cozy.bar.init({
    appName: 'Files',
    iconPath: require('../../../vendor/assets/app-icon.svg'),
    lang: 'en'
  })
}

export const isClientRegistered = async (client) => {
  return await cozy.client.auth.getClient(client).then(client => true).catch(() => false)
}

export function resetClient () {
  // reset cozy-bar
  // TODO
  // reset pouchDB
  cozy.client.offline.destroyAllDatabase()
  // reset cozy-client-js
  cozy.client._storage.clear()
}

@@ -1104,19 +1104,229 @@
 tch(
-() =%3E false
+err =%3E %7B%0A    if (err.message === 'Client has been revoked') %7B%0A      return false%0A    %7D%0A    // this is the error sent if we are offline%0A    if (err.message === 'Failed to fetch') %7B%0A      return true%0A    %7D%0A    throw err%0A  %7D
 )%0A%7D%0A

handle offline scenario related to https://github.com/cozy/cozy-client-js/pull/105