package ru.micord.ervu.account_applications.component.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import model.FieldData;
import ru.micord.ervu.account_applications.component.field.persist.ErvuFormLoadComponent;

import ru.cg.webbpm.modules.webkit.beans.Behavior;

/**
 * @author Adel Kalimullin
 */
public final class FormUtils {

  private FormUtils() {
  }

  public static List<FieldData> createFieldData(Map<String, List<String>> fieldNameAndGuidsMap,
      Map<String, Object> fieldNameAndValueMap) {
    List<FieldData> fieldData = new ArrayList<>();

    fieldNameAndValueMap.forEach((fieldName, value) -> {
      List<String> guids = fieldNameAndGuidsMap.get(fieldName);
      if (guids != null) {
        guids.forEach(guid -> fieldData.add(new FieldData(guid, value)));
      }
    });

    return fieldData;
  }

  public static Map<String, List<String>> getComponentNameToIdMap(Behavior behavior) {
    return utils.FormUtils.getFormComponents(behavior, ErvuFormLoadComponent.class)
        .stream()
        .collect(Collectors.toMap(
            component -> component.fieldName,
            component -> Collections.singletonList(component.getObjectId()),
            (existing, newValue) -> {
              List<String> merged = new ArrayList<>(existing);
              merged.addAll(newValue);
              return merged;
            }
        ));
  }
}
