package com.boot.security.server.page.table;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.boot.security.server.model.AdvertiserData;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 分页查询处理器
 * 
 * @author maliang
 *
 */

public class PageTableHandler {

	private CountHandler countHandler;
	private ListHandler listHandler;
	private OrderHandler orderHandler;

	public PageTableHandler(CountHandler countHandler, ListHandler listHandler) {
		super();
		this.countHandler = countHandler;
		this.listHandler = listHandler;
	}

	public PageTableHandler(CountHandler countHandler, ListHandler listHandler, OrderHandler orderHandler) {
		this(countHandler, listHandler);
		this.orderHandler = orderHandler;
	}

	public static <E> String getJSONObject(List<E> list,Integer count){
		JSONObject jsonObject = new JSONObject();
		JSONArray array = new JSONArray();
		Iterator<E> iterator = list.iterator();
		while (iterator.hasNext()){
			array.add(JSONObject.toJSON(iterator.next()));
		}
		jsonObject.put("data",array);
		jsonObject.put("count",count);
		jsonObject.put("code",0);
		return jsonObject.toJSONString();
	}

	public PageTableResponse handle(PageTableRequest dtRequest) {
		int count = 0;
		List<?> list = null;

		count = this.countHandler.count(dtRequest);
		if (count > 0) {
			if (orderHandler != null) {
				dtRequest = orderHandler.order(dtRequest);
			}
			list = this.listHandler.list(dtRequest);
		}

		if (list == null) {
			list = new ArrayList<>();
		}

		return new PageTableResponse(count, count, list);
	}

	public interface ListHandler {
		List<?> list(PageTableRequest request);
	}

	public interface CountHandler {
		int count(PageTableRequest request);
	}

	public interface OrderHandler {
		PageTableRequest order(PageTableRequest request);
	}
}