import Ember from 'ember'
export default Ember.Component.extend
  #tagName: 'h4'
  classNames: ['workflow-instance-workflow-group-title']
  make_editable: (->
    @set('workflow_group.isEditing', true)
    @$('.workflow-group-title-edit').focus()
  ).on "doubleClick"
  #focusOut: -> @send('saveWorkflowStep') if @get('workflow_group.isEditing')
  workflow_group_name: Ember.computed.oneWay 'workflow_group.name'
  select_title: (->
    @$('.workflow-group-title-edit').focus() if @get('workflow_group.isEditing')
  ).on('didRender')

  actions:
    newWorkflowActionDefinition: ->
      workflow_group = @get('workflow_group')
      #title = "WorkflowActionDefinition #{workflow_group.store.peekAll('panda/workflow-action-definition').get('length') + 1}"
      title = ""
      if last_workflow_action_definition = workflow_group.get('sorted_workflow_action_definitions.lastObject')
        position = 1 + last_workflow_action_definition.get('position') # can be a gap due to deleted actions not updating the rest
      else
        position = 0

      workflow_action_definition = @store.createRecord 'panda/workflow_action_definition',
        title: title
        position: position
        workflow_group: workflow_group
        project: workflow_group.get('project')
      @modal 'workflow-action-definition/edit-workflow-action-definition', model: workflow_action_definition

    saveWorkflowStep: ->
      return unless workflow_group_name = @get('workflow_group_name')
      workflow_group = @get('workflow_group')
      workflow_group.set 'name', workflow_group_name
      workflow_group.set 'isEditing', false
      workflow_group.save()
    rollbackWorkflowStep: ->
      #@get('workflow_group').rollbackAttributes()
      @set 'workflow_groupName', @get('workflow_group.name')
      @set 'workflow_group.isEditing', false
    destroyWorkflowStep: ->
      @modal 'confirm',
        title_path: 'general.destroy.are_you_sure'
        model: @get('workflow_group')
        ok: ->
          workflow_group = @get('model')
          workflow_group.rollbackAttributes()
          workflow_group.destroyRecord()
        close: ->
          workflow_group = @get('model')
          workflow_group.set "isEditing", false
    displayWorkflowActionDefinitions: ->
      @modal 'display-workflow-action-definitions',
        model: Ember.A([@get('workflow_group')])
        title: @get('workflow_group.name')

    sortWorkflowActionDefinitions: ->
      @modal 'sort-records',
        model: @get('workflow_group.workflow_action_definitions')
        title: "Arrange workflow actions for step #{@get('workflow_group.name')} of project #{@get('workflow_group.project.name')}"

    editWorkflowGroup: ->
      @modal 'project/edit-workflow-group',
        model: @get('workflow_group')
