xhr           = require('xhr')
_             = require('lodash')
metrics       = require('./metrics.coffee')

SETTINGS =
  locale: LOCALE
  host: "//www.jetradar.com/autocomplete/places"
  max: 6

callback_stub = (data) -> console.log(data)

_cache = {}

module.exports = (settings = {}) ->

  settings = _.extend(SETTINGS, settings)

  _running = null

  _aborted = false

  load: (term, callback = callback_stub) ->
    callbacks = if !_.isArray(callback)
        [callback]
      else
        callback

    if _running
      _aborted = true
      _running.abort()

    if _cache[term]
      _.each(callbacks, (c) -> c(_cache[term]))
      return

    _running = xhr({
        uri: "#{settings.host}?locale=#{settings.locale}&q=#{encodeURIComponent(term)}&with_countries=false"
        method: "get"
        useXDR: true
      }, (err, res, body) =>
        if typeof body == "string"
          body = JSON.parse(body)

        if err
          if !_aborted
            metrics.reach_goal('AUTOCOMPLETE_ERROR')
        else
          _cache[term] = body
          _.each(callbacks, (c) -> c(body))
        _aborted = false
    )
