import ModalBase from 'ember-cli-dunlop/mixins/modal-base'
ESC_KEY = 27
export default ModalBase.extend
  title: Ember.computed 'model.workflow_action_definition.title', ->
    t 'project.edit_instance_action.title', title: @get('model.workflow_action_definition.title')
  value_type: Ember.computed.alias 'model.workflow_action_definition.value_type'
  string_value: ''
  number_value: null
  text_value: ''
  new_note_content: ''
  new_note_content_is_blank: Ember.computed.not 'new_note_content.length'
  has_uncompleted_constraints: false
  #attached_instance_action_connections: []
  attached_conditions_not_met_warning: ''

  can_edit_action: Ember.computed 'model.workflow_action_definition.organization.users.[]', ->
    return true if @get('globals.current_user.admin')
    return true if @get('model.workflow_action_definition.offset_type') is 'attached'
    role_names = @get('globals.current_user.role_names') || []
    return true if 'manage-app-panda' in role_names
    return true if 'manage-model-panda/project-instance' in role_names
    organization_user_ids = @get('model.workflow_action_definition.organization.users')?.mapBy('id') || []
    return true if @get('globals.current_user.id') in organization_user_ids
    false

  _initEscListener: ->
    closeOnEscapeKey = (ev) =>
      @send 'rollback_and_close' if ev.keyCode is ESC_KEY
    Ember.$('body').on('keyup.modal-dialog', closeOnEscapeKey)
    false

  note_events: Ember.computed 'model.events.@each.event_value', ->
    @get('model.events').filterBy('event_key', 'note')

  misc_events: Ember.computed 'model.events.length', ->
    @get('model.events').rejectBy('event_key', 'note')



  willOpenModal: ->
    @_initEscListener()
    @get('model.events').reload()
    @set 'string_value',    @get('model.string_value')
    @set 'number_value',    @get('model.number_value')
    @set 'text_value',      @get('model.text_value')
    @set 'timestamp_value', @get('model.timestamp_value')
    #@set 'attached_instance_action_connections', []
    # set this action here to be able to propagate the save callback. This makes double nested attached actions work smoothly
    @set 'actions.open_current_modal', -> @modal 'project/edit-instance-action', model: @get('model'), save: @get('modal_options.save')

    # constraints setup
    #@set 'attached_conditions_not_met_warning', 'validating attached actions...' # important te reset since attached actions can be completed on re-open of parent
    @set 'attached_conditions_not_met_warning', ''
    @set 'has_uncompleted_constraints', false
    base = @
    @get('model.pointing_project_instance_action_connections').then (pointing_connections) =>
      pointing_connections.forEach (pointing_connection) ->
        return if base.get('has_uncompleted_constraints') # already found, no need to search further
        pointing_connection.get('project_instance_action').then (pointing_project_instance_action) ->
          return if pointing_project_instance_action.get('completed')
          if pointing_connection.get('connection_type') is 'constraint'
            return base.set 'has_uncompleted_constraints', true
          if pointing_connection.get('connection_type') is 'attached'
            if conditional_value = pointing_connection.get('conditional_base_value')
              if base.get('model.workflow_action_definition.value_type') isnt 'select' or conditional_value is base.get('model.string_comparison_value')
                pointing_project_instance_action.get('workflow_action_definition').then (pointing_workflow_action_definition) ->
                  base.set 'attached_conditions_not_met_warning', "#{pointing_workflow_action_definition.get('title')} not completed"

  select_class_names: Ember.computed 'model.string_value', ->
    return ['green']
    if @get('model.string_value') then 'green button' else 'button'


  has_changed_timestamp_value: Ember.computed 'timestamp_value', 'model.timestamp_value', ->
    current_timestamp = @get('timestamp_value')
    model_timestamp = @get('model.timestamp_value')
    return false unless current_timestamp or model_timestamp # both false, nothing changed
    return true unless current_timestamp and model_timestamp
    # now we have two timestamps, lets compare
    current_timestamp.toISOString() isnt model_timestamp.toISOString()

  actions:
    set_value: (attribute, value) ->
      #@set attribute, value # internal setting for validation
      @set 'action_value', value
      @set "model.#{attribute}", value
      @send 'validate_and_progress'

    set_string_value: ->
      @send 'set_value', 'string_value', @get('string_value')

    set_text_value: ->
      @send 'set_value', 'text_value', @get('text_value')

    set_number_value: ->
      @send 'set_value', 'number_value', @get('number_value')

    set_timestamp_value: ->
      @send 'set_value', 'timestamp_value', @get('timestamp_value')

    close: ->
      Ember.$('body').off('keyup.modal-dialog')
      @_super arguments...

    continue_from_inquiry: ->
      record = @get('model')
      #state = 'active'
      #state = 'overdue' if @get('model.target_date')?.clone().add(record.get('workflow_action_definition.overdue_coulance') ,'day').format('YYYY-MM-DD') < moment().format('YYYY-MM-DD')
      #record.set 'state', state
      #record.save().then ->
      #  record.get('events').reload()
      record.triggerEvent(event_key: 'state', event_value: 'active').then -> record.get('events').reload()

    add_new_note: ->
      return unless content = @get('new_note_content')
      now = moment()
      new_note_event = @store.createRecord 'panda/action-event',
        client_identifier: @get('model.project_instance.client_identifier')
        identifier: @get('model.workflow_action_definition.identifier')
        event_key: 'note'
        event_value: content
        event_timestamp: now
      new_note_event.save().then =>
        @get('model.events').pushObject new_note_event
        @set 'new_note_content', ''
        #@send 'close'

    start_inquiry: ->
      record = @get('model')
      #record.set 'state', 'inquiry'
      #record.save().then => @send 'add_new_note'
      record.triggerEvent(event_key: 'state', event_value: 'inquiry', note: @get('new_note_content')).then =>
        record.get('events').reload()
        @set 'new_note_content', ''

      #record.save().then ->
      #  record.get('events').reload()

    validate_and_progress: ->
      # these validations are only needed for select value_type actions, since all the others have no dynamic values that will limit the progress
      all_attached_actions_are_valid = true
      @set 'attached_conditions_not_met_warning', ''
      @get('model.pointing_project_instance_action_connections').forEach (pointing_connection) =>
        if pointing_connection.get('connection_type') is 'attached'
          if conditional_value = pointing_connection.get('conditional_base_value')
            if conditional_value is @get('model.string_comparison_value') and not pointing_connection.get('project_instance_action.completed')
              @set 'attached_conditions_not_met_warning', "#{pointing_connection.get('project_instance_action.workflow_action_definition.title')} not completed"
              all_attached_actions_are_valid = false
              #alert 'Attached not completed'
      @send('saveRecord') if all_attached_actions_are_valid
