package mil.dds.anet.beans.lists;

import io.leangen.graphql.annotations.GraphQLInputField;
import io.leangen.graphql.annotations.GraphQLQuery;
import java.util.List;
import org.jdbi.v3.core.mapper.RowMapper;
import org.jdbi.v3.core.statement.Query;

public class AnetBeanList<T> {

  @GraphQLQuery
  @GraphQLInputField
  List<T> list;
  @GraphQLQuery
  @GraphQLInputField
  Integer pageNum;
  @GraphQLQuery
  @GraphQLInputField
  Integer pageSize;
  @GraphQLQuery
  @GraphQLInputField
  Integer totalCount;

  public AnetBeanList() { /* Serialization Constructor */ }

  public AnetBeanList(List<T> list) {
    this(null, null, list);
    this.totalCount = list.size();
  }

  public AnetBeanList(Integer pageNum, Integer pageSize, List<T> list) {
    this.pageNum = pageNum;
    this.pageSize = pageSize;
    this.list = list;
  }

  public AnetBeanList(Query query, int pageNum, int pageSize, RowMapper<T> mapper) {
    this(pageNum, pageSize, query.map(mapper).list());
    int resultSize = getList().size();
    if (resultSize == 0) {
      setTotalCount(0);
    } else {
      Integer foundCount = (Integer) query.getContext().getAttribute("totalCount");
      setTotalCount(foundCount == null ? resultSize : foundCount);
    }
  }

  public List<T> getList() {
    return list;
  }

  public void setList(List<T> list) {
    this.list = list;
  }

  public Integer getPageNum() {
    return pageNum;
  }

  public void setPageNum(Integer pageNum) {
    this.pageNum = pageNum;
  }

  public Integer getPageSize() {
    return pageSize;
  }

  public void setPageSize(Integer pageSize) {
    this.pageSize = pageSize;
  }

  public Integer getTotalCount() {
    return totalCount;
  }

  public void setTotalCount(Integer totalCount) {
    this.totalCount = totalCount;
  }

}

@@ -975,69 +975,181 @@
     
+f
 in
-t resultSize = getList().size();%0A    if (resultSize == 0) %7B
+al Integer foundCount = (Integer) query.getContext().getAttribute(%22totalCount%22);%0A    if (foundCount != null) %7B%0A      // Total count was found in the query results, use it
 %0A   
@@ -1169,9 +1169,18 @@
 unt(
-0
+foundCount
 );%0A 
@@ -1201,150 +1201,397 @@
     
-Integer foundCount = (Integer) query.getContext().getAttribute(%22totalCount%22);%0A      setTotalCount(foundCount == null ? resultSize : foundCount
+// Get the number of results actually retrieved%0A      int resultSize = getList().size();%0A      // Check if that is zero%0A      if (resultSize == 0) %7B%0A        // We may have a pagination overshoot, so set the size to the last item on the previous page%0A        resultSize = pageNum * pageSize;%0A      %7D%0A      // Make sure size is always non-negative%0A      setTotalCount(Math.max(0, resultSize)
 );%0A 

Return a better estimate of totalCount when no rows are found