import Ember from 'ember'
# get_active_workflow_action_definitions(workflow_action_definitions, project_scenarios, set_operation = 'union or intersection')
# this util takes as first arguments the workflow_action_definitions scope
# and tries to apply filtering based on the given project_scenarios and set_operation

get_active_workflow_action_definitions_using_union = (project_scenarios) ->
  selected_project_scenario_workflow_action_definition_ids = []
  working_workflow_action_definitions = []
  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
  working_workflow_action_definitions

get_active_workflow_action_definitions_using_intersection = (workflow_action_definitions, project_scenarios) ->
  selected_project_scenario_workflow_action_definition_ids = []
  first_run = true
  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
  workflow_action_definitions.filter((r) -> r.get('id') in selected_project_scenario_workflow_action_definition_ids)

get_active_workflow_action_definitions = (workflow_action_definitions, project_scenarios, set_operation = 'union') ->
  project_scenarios = Ember.makeArray(project_scenarios)
  workflow_action_definitions = workflow_action_definitions.toArray()
  # initialize unused working workflow-action-definitions
  if project_scenarios.length
    if set_operation is 'intersection'
      get_active_workflow_action_definitions_using_intersection(workflow_action_definitions, project_scenarios)
    else
      get_active_workflow_action_definitions_using_union(project_scenarios)
  else
    # no filtering can be allplied, return all
    workflow_action_definitions

export { get_active_workflow_action_definitions_using_union }
export { get_active_workflow_action_definitions_using_intersection }
export { get_active_workflow_action_definitions }

export default get_active_workflow_action_definitions
