   test: 'http://localhost:7357'
   _cam: 'http://172.17.2.87:3000'
 
-DEFAULT_ENV = '_cam'
+API_APPLICATION_IDS =
+  _cam: '05fd85e729327b2f71cda394d8e87e042e0b77b05e05280e8246e8bdb05d54ed'
 
 JSON_HEADERS =
   'Accept': 'application/json'


api.host = API_HOSTS[process.env.NODE_ENV ? DEFAULT_ENV]

api.client = new JSONAPIClient api.host + '/api',
  'Content-Type': 'application/vnd.api+json; version=1'
  'Accept': 'application/vnd.api+json; version=1'

api.projects = api.client.createType 'projects'

# Proxy the client's HTTP methods to the API object.
for method in ['post', 'get', 'put', 'delete']
  api[method] = api.client[method].bind api.client

api.auth =
  currentToken: ''
  currentSession: null

  getAuthToken: ->
    if @currentToken
      Promise.resolve @currentToken
    else
      makeHTTPRequest('GET', api.host + '/users/sign_up', null, null, ADD_CREDENTIALS).then (request) =>
        [_, authTokenMatch1, authTokenMatch2] = request.responseText.match CSRF_TOKEN_PATTERN
        @currentToken = authTokenMatch1 ? authTokenMatch2
        @currentToken

  register: ({login, email, password, passwordConfirmation}) ->
    api.auth.currentSession = @getAuthToken().then (token) ->
      data =
        authenticity_token: token
        user:

          password: password
          password_confirmation: passwordConfirmation

      makeHTTPRequest('POST', api.host + '/users', data, JSON_HEADERS, ADD_CREDENTIALS).then []...,
        (request) ->
          response = JSON.parse request.responseText
          console?.log 'Created user', response
          response

        (error) ->
          console?.error 'Failed to register', error
          null

  getCurrentUser: ->
    # TODO: Check to see if anybody's signed in.

  signIn: ({login, password}) ->
    @currentUser = @getAuthToken().then (token) =>
      data =
        authenticity_token: token
        user:
          login: login
          password: password

      makeHTTPRequest('POST', api.host + '/users/sign_in', data, JSON_HEADERS, ADD_CREDENTIALS).then []...,
        (request) =>
          console?.log 'Signed in successfully as', login

          # This route returns a JSON-API `users` resource.
          api.client.processResponseTo request

          Promise.all([@getBearerToken(), api.users.get {login}, 1]).then ([token, [user]]) ->
            console?.log 'Current user', user
            user

        (error) ->
          console?.error 'Failed to sign in', error
          null

  signOut: ->
    @getAuthToken().then (token) ->
      data =
        authenticity_token: token

      makeHTTPRequest('DELETE', api.host + '/users/sign_out', data, JSON_HEADERS, ADD_CREDENTIALS).then []...,
        (request) =>
          response = JSON.parse request.responseText
          console?.log 'Signed out', response
          @deleteBearerToken()
          response

        (error) ->
          console?.log 'Failed to sign out', error

module.exports = api
window?.api = api
