import ModalBase from 'ember-cli-dunlop/mixins/modal-base'
import lookupValidator from 'ember-changeset-validations'
import Changeset from 'ember-changeset'
import ModelValidations from 'ember-panda/validations/project'
validator = lookupValidator(ModelValidations)
import config from 'ember-get-config'
{get} = Ember
export default ModalBase.extend
  session: Ember.inject.service('session')
  contract: null
  willOpenModal: ->
    dummy = Ember.Object.create
      name: '' # new project name
    changeset = new Changeset(dummy, validator, ModelValidations)
    @set 'changeset', changeset

  actions:
    set_contract: (file) ->
      @set 'file', file
      failure = ((message) ->
        @set 'contract', null
        @set 'alert_message', message
      ).bind @
      file.readAsText().then (result) =>
        try
          contract = JSON.parse(result)
          return failure 'Contract has no version' unless contract.contract_version?
          @set 'contract', contract
          @set 'alert_message', null
        catch error
          failure 'Cannot parse JSON'
    saveRecord: ->
      @get('changeset').validate()
      component = @
      if @get('changeset.isValid')
        file = @get('file')
        model_name = 'panda/project'
        base_url = @store.adapterFor(model_name).buildURL(model_name)
        endpoint = "#{base_url}/new_from_contract"
        session = @get('session')
        #TODO implement generic request feature, this is not the way to do it! Done because it works and no time
        if get(session, 'isAuthenticated')
          session.authorize 'authorizer:devise', (key, authorization) =>
            file.upload(endpoint, data: {name: @get('changeset.name')}, headers: "#{key}": authorization).then (response) ->
              if response.body?.errors?.length
                component.set 'alert_message', response.body.errors.join('<br>')
                component.set 'contract', null
              else
                component.store.pushPayload response.body if response.body?.data?.id
                component.send 'close'
        else # assume same host authenticated rails session
          file.upload(endpoint, data: {name: @get('changeset.name')}).then (response) ->
            component.send 'close'
