import {tolerant_selector} from './base'
import {array_from_hash, split_array, property_getter, property_is} from '../common/utilities'
import {action_reject_demand, action_accept_demand} from '../common/demands'

const get_raw_demands = (state) => state.demands.demands
const get_raw_users = (state) => state.users.users
const get_recruiter_id = (state) => state.profile.id

export const get_demands = tolerant_selector(
  [get_raw_demands, get_raw_users, get_recruiter_id],
  (demands, users, recruiter_id) => split_array(
    array_from_hash(demands).map((demand) => ({
      ...demand,
      user: users[demand.user_id],
      status: demand.accepted_at ? "accepted" : (demand.rejected_at ? "rejected" : "pending"),
      accept: () => action_accept_demand(demand.id),
      reject: () => action_reject_demand(demand.id),
    })).filter(property_getter("user")).filter(property_is("recruiter_id", recruiter_id)),
    property_getter("status"),
    ["accepted", "rejected", "pending"],
  )
)
