import { all, call, put, select, takeLatest } from "redux-saga/effects";
import GetJobTarget from "../../util/GetJobTarget";
import { setSelectedJobTargetPcSuccess } from "./application.actions";
import ApplicationActionTypes from "./application.types";

export function* onSetTargetPc() {
  yield takeLatest(ApplicationActionTypes.SET_SELECTED_JOB_TARGET_PC, CalculateTarget);
}
export function* CalculateTarget({ payload }) {
  const { group, v_age, close_date, v_mileage, job } = payload;

  const { targets, ins_rule_set } = yield select((state) => state.user.bodyshop);

  yield put(setSelectedJobTargetPcSuccess(GetJobTarget({ group, v_age, targets, close_date, v_mileage, job, ins_rule_set })));
  // const targetsForGroup = targets.filter((t) => t.group === group);
  // if (!targetsForGroup) return 0;
  // const targetPc = targetsForGroup.filter(
  //   (t) => t.ageGte <= v_age && (t.ageLt ? t.ageLt > v_age : true)
  // );
  // if (targetPc.length === 0) yield put(setSelectedJobTargetPcSuccess(100));
  // else if (targetPc.length === 1)
  //   yield put(setSelectedJobTargetPcSuccess(targetPc[0].target));
  // else {
  //   yield put(setSelectedJobTargetPcSuccess(100));
  // }
}

export function* applicationSagas() {
  yield all([call(onSetTargetPc)]);
}
