package com.jpsoft.shinestar.modules.common.utils;

import com.github.dozermapper.core.DozerBeanMapperBuilder;
import com.github.dozermapper.core.Mapper;
import com.github.pagehelper.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.HashMap;
import java.util.Map;

public class PojoUtils {
    private static Logger logger = LoggerFactory.getLogger("root");
    private static Mapper MAPPER = DozerBeanMapperBuilder.buildDefault();

    public static <T> T map(Object source, Class<T> destinationClass) {
        if (source == null) {
            return null;
        }
        return MAPPER.map(source, destinationClass);
    }

    public static void map(Object source, Object destination) {
        MAPPER.map(source, destination);
    }

    public static <T> Map<String, Object> pojo2map(T t) {
        // TODO Auto-generated method stub
        Map<String,Object> map = new HashMap<String,Object>();

        try{
            BeanInfo beanInfo  = Introspector.getBeanInfo(t.getClass());
            PropertyDescriptor[] props = beanInfo.getPropertyDescriptors();

            for (PropertyDescriptor pd : props) {
                if (pd.getReadMethod()!=null) {
                    try {
                        Object srcValue = pd.getReadMethod().invoke(t);
                        map.put(pd.getName(), srcValue);
                    }
                    catch (Exception ex){
                        logger.error(ex.getMessage(),ex);
                    }
                }
            }
        }
        catch(Exception ex){
            ex.printStackTrace();
        }

        return map;
    }

    public static Map pageWrapper(Page page){
        Map<String,Object> pageMap = new HashMap<>();

        pageMap.put("recordsTotal",page.getTotal());
        pageMap.put("recordsFiltered",page.getTotal());
        pageMap.put("totalPage",page.getPages());
        pageMap.put("pageNumber",page.getPageNum());
        pageMap.put("pageSize",page.getPageSize());
        pageMap.put("data", page.getResult());

        return pageMap;
    }

    public static <T> Page<T> convertPage(Page page, Class<T> destinationClass){
        Page newPage = new Page();

        newPage.setPageNum(page.getPageNum());
        newPage.setPageSize(page.getPageSize());
        newPage.setPages(page.getPages());
        newPage.setTotal(page.getTotal());

        for (Object obj: page) {
            newPage.add(map(obj,destinationClass));
        }

        return newPage;
    }
}
