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

get_active_workflow_groups_using_union = (project_scenarios) ->
  selected_project_scenario_workflow_group_ids = []
  working_workflow_groups = []
  project_scenarios.forEach (selected_project_scenario) ->
    selected_project_scenario.get('workflow_groups').forEach (workflow_group) ->
      if selected_project_scenario_workflow_group_ids.indexOf(workflow_group.get('id')) < 0
        selected_project_scenario_workflow_group_ids.push workflow_group.get('id')
        working_workflow_groups.push workflow_group
  working_workflow_groups

get_active_workflow_groups_using_intersection = (workflow_groups, project_scenarios) ->
  selected_project_scenario_workflow_group_ids = []
  first_run = true
  project_scenarios.forEach (selected_project_scenario) ->
    current_workflow_group_ids = selected_project_scenario.get('workflow_groups').mapBy('id').toArray()
    if first_run
      selected_project_scenario_workflow_group_ids =  current_workflow_group_ids
      first_run = false
      return
    selected_project_scenario_workflow_group_ids = selected_project_scenario_workflow_group_ids.filter (id) -> id in current_workflow_group_ids
  workflow_groups.filter((r) -> r.get('id') in selected_project_scenario_workflow_group_ids)

get_active_workflow_groups = (workflow_groups, project_scenarios, set_operation = 'union') ->
  project_scenarios = Ember.makeArray(project_scenarios)
  workflow_groups = workflow_groups.toArray()
  # initialize unused working workflow-groups
  if project_scenarios.length
    if set_operation is 'intersection'
      get_active_workflow_groups_using_intersection(workflow_groups, project_scenarios)
    else
      get_active_workflow_groups_using_union(project_scenarios)
  else
    # no filtering can be allplied, return all
    workflow_groups

export { get_active_workflow_groups_using_union }
export { get_active_workflow_groups_using_intersection }
export { get_active_workflow_groups }

export default get_active_workflow_groups
