/* globals gapi */

import _ from 'lodash/fp'

import config from '../../config.js'
import notifier from './components/Notifier.js'

const Constants = {
  Scopes: [
    'https://mail.google.com/',
    'https://www.googleapis.com/auth/youtube.readonly',
  ],
  DiscoveryDocs: [
    'https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest',
    'https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest',
  ],
}

const loadScript = new Promise(resolve => {
  const $script = document.createElement('script')
  $script.src = 'https://apis.google.com/js/api.js'
  $script.addEventListener('load', resolve)
  $script.setAttribute('async', 'async')
  $script.setAttribute('defer', 'defer')

  const $firstScript = document.getElementsByTagName('script')[0]
  $firstScript.parentNode.insertBefore($script, $firstScript)
  notifier.persist('parser', 'Loading Google api...')
})

const loadApi = () => new Promise(_.curry(gapi.load)('client:auth2'))

const initApi = () => {
  notifier.persist('parser', 'Initializing api...')
  return gapi.client.init({
    discoveryDocs: Constants.DiscoveryDocs,
    scope: Constants.Scopes.join(' '),
    clientId: config.CLIENT_ID,
  })
}

export default loadScript
  .then(loadApi)
  .then(initApi)

