package com.persagy.bdtp.adm.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.persagy.bdtp.adm.common.AdmResult;
import com.persagy.bdtp.adm.entity.Pagination;
import com.persagy.bdtp.adm.entity.oldadm.OldAdmResult;
import com.persagy.dmp.basic.model.QueryCriteria;
import com.persagy.dmp.common.model.response.CommonResult;

import java.util.List;
import java.util.function.Supplier;

public class ServiceUtil {

	public static final String SYNC_APP_IMPL = "syncAppImpl";

	private static final String SUCCESS = "success";

	public static QueryCriteria getQueryCriteria(ObjectMapper objectMapper, String... objType){
		QueryCriteria queryCriteria = new QueryCriteria();

		ObjectNode objectNode = objectMapper.createObjectNode();
		if(objType.length  == 1)
			objectNode.put("objType", objType[0]);
		else if(objType.length > 1) {
			ArrayNode arrayNode = objectNode.putArray("objType");
			for(String type : objType) {
				arrayNode.add(type);
			}
		}

		queryCriteria.setCriteria(objectNode);
		return queryCriteria;
	}

	public static <T> T call(Supplier<CommonResult<T>> action) {
		return call(action, null);
	}

	private static <T> T call(Supplier<CommonResult<T>> action, Pagination pagination) {
		CommonResult<T> result = action.get();
		if(SUCCESS.equals(result.getResult())) {
			if(pagination != null)
				pagination.setTotal(result.getCount().intValue());
			return result.getData();
		}
		throw new CallException(new AdmResult<>(result.getResult(), result.getMessage()));
	}

	public static <T> List<T> queryAllPage(Supplier<CommonResult<List<T>>> action, QueryCriteria criteria, Pagination pagination){
		List<T> list = null;
		while (pagination.isHasNext()){
			criteria.setPage((long)pagination.getPageNum());
			criteria.setSize((long)pagination.getPageSize());
			if(list == null)
				list = ServiceUtil.call(action, pagination);
			else
				list.addAll(ServiceUtil.call(action, pagination));
			pagination.next();
		}
		return list;
	}


	public static <T> T callOldAdm(Supplier<OldAdmResult<T>> action, Pagination pagination) {
		OldAdmResult<T> result = action.get();
		if(SUCCESS.equals(result.getResult())) {
			if(pagination != null)
				pagination.setTotal(result.getTotal());
			return result.getContent();
		}
		throw new CallException(new AdmResult<>(result.getResult(), result.getMessage()));
	}

	public static <T> T callOldAdm(Supplier<OldAdmResult<T>> action) {
		return callOldAdm(action, null);
	}

}
