import Ember from 'ember'

export default Ember.Mixin.create
  selected_project_scenarios: [] # null
  selected_project_scenarios_set_operation: 'union' # union or intersection
  active_workflow_action_definitions: []
  active_workflow_action_definition_ids: []

  set_active_workflow_action_definitions: ->
    # initialize unused working workflow-action-definitions
    if @get('selected_project_scenarios.length')
      if @get('selected_project_scenarios_set_operation') is 'intersection'
        @set_active_workflow_action_definitions_using_intersection()
      else
        @set_active_workflow_action_definitions_using_union()
    else
      @set 'active_workflow_action_definitions', @get('project.workflow_action_definitions') || []
      @set 'active_workflow_action_definition_ids', @get('active_workflow_action_definitions').mapBy('id').toArray()

  set_active_workflow_action_definitions_using_union: ->
    selected_project_scenario_workflow_action_definition_ids = []
    working_workflow_action_definitions = []
    @get('selected_project_scenarios').forEach (selected_project_scenario) ->
      selected_project_scenario.get('workflow_action_definitions').forEach (workflow_action_definition) ->
        if selected_project_scenario_workflow_action_definition_ids.indexOf(workflow_action_definition.get('id')) < 0
          selected_project_scenario_workflow_action_definition_ids.push workflow_action_definition.get('id')
          working_workflow_action_definitions.push workflow_action_definition
    @set 'active_workflow_action_definitions', working_workflow_action_definitions
    @set 'active_workflow_action_definition_ids', selected_project_scenario_workflow_action_definition_ids

  set_active_workflow_action_definitions_using_intersection: ->
    selected_project_scenario_workflow_action_definition_ids = []
    first_run = true
    @get('selected_project_scenarios').forEach (selected_project_scenario) ->
      current_workflow_action_definition_ids = selected_project_scenario.get('workflow_action_definitions').mapBy('id').toArray()
      if first_run
        selected_project_scenario_workflow_action_definition_ids =  current_workflow_action_definition_ids
        first_run = false
        return
      selected_project_scenario_workflow_action_definition_ids = selected_project_scenario_workflow_action_definition_ids.filter (id) -> id in current_workflow_action_definition_ids

    @set 'active_workflow_action_definition_ids', selected_project_scenario_workflow_action_definition_ids
    @set 'active_workflow_action_definitions', @get('project.workflow_action_definitions').filter((r) -> r.get('id') in selected_project_scenario_workflow_action_definition_ids)

