package com.pingcap.community.blogserver.util;

import com.blazebit.persistence.querydsl.BlazeJPAQuery;
import com.querydsl.core.types.dsl.ComparableExpressionBase;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import java.util.Map;

public class QueryUtils {

  public static <T> BlazeJPAQuery<T> queryByPageable(BlazeJPAQuery<T> query, Map<String, ComparableExpressionBase<?>> map, Pageable pageable) {
    query.offset(pageable.getOffset()).limit(pageable.getPageSize());
    Sort sort = pageable.getSort();
    sort.stream().forEach((s) -> {
      Sort.Direction direction = s.getDirection();
      String property = s.getProperty();
      if (map.containsKey(property)) {
        ComparableExpressionBase<?> path = map.get(property);
        if (direction.isDescending()) {
          query.orderBy(path.desc());
        } else {
          query.orderBy(path.asc());
        }
      }
    });
    return query;
  }

  public static <T, V extends Comparable<V>> void eqIfNotNull (BlazeJPAQuery<T> query, ComparableExpressionBase<V> path, V value) {
    if (value != null) {
      query.where(path.eq(value));
    }
  }

}
