package ervu_dashboard.component.filter;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import model.FilterModel;
import model.filter.FilterableReference;

import ru.cg.webbpm.modules.database.bean.filter.EntityFilter;
import ru.cg.webbpm.modules.standard_annotations.scopes.AnalyticalScope;
import ru.cg.webbpm.modules.standard_annotations.validation.NotNull;
import ru.cg.webbpm.modules.webkit.annotations.Model;
import ru.cg.webbpm.modules.webkit.beans.Behavior;

/**
 * @author Vitaly Chekushkin
 */
@Model
@AnalyticalScope(FilterableReference.class)
public class FilterReferences extends Behavior {

  @NotNull
  public FilterReference[] references;

  private final Map<String, FilterReference> referenceMap = new HashMap<>();

  @Override
  protected void start() {
    super.start();
    Arrays.stream(references).forEach(reference -> referenceMap.put(reference.getSupportsFilterGuid(), reference));
  }

  public EntityFilter toEntityFilter(String filterGuid, FilterModel filterModel) {
    return Optional.ofNullable(referenceMap.get(filterGuid))
        .map(reference -> reference.toEntityFilter(filterModel))
        .orElseThrow(() -> new IllegalArgumentException(
            "Filter reference for guid=%s(id:%s) not defined".formatted(
                filterGuid, filterGuid
            ))
        );
  }
}
