import get from 'lodash/get';
import set from 'lodash/set';

export function customizeListData(
  toObj: any,
  fromObj: any,
  pathTo: string,
  pathFrom: string,
  conditionFn: any, // todo fn type
  keys?: string[] | undefined
) {
  const targetArray: any[] = get(toObj, pathTo);
  const dataArray: any[] = get(fromObj, pathFrom);

  if (!Array.isArray(targetArray) || !Array.isArray(dataArray)) {
    return toObj;
  }

  const result = targetArray.map((targetEl: any) => {
    dataArray.forEach((dataEl: any) => {
      if (conditionFn(targetEl, dataEl)) {
        targetEl = addValues(targetEl, dataEl, keys);
      }
    });

    return targetEl;
  });

  set(toObj, pathTo, result);

  return toObj;
}

function addValues(to: any, from: any, keys?: string[] | undefined) {
  if (keys) {
    keys.forEach((key) => {
      to[key] = from[key];
    });
    return to;
  } else {
    return Object.assign({}, to, from);
  }
}
