/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights reserved. <a>http://www.crunii.com</a>
 */
package com.crunii.micro.common.utils;

import java.beans.PropertyDescriptor;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.ConvertUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.util.ObjectUtils;

import com.crunii.micro.common.converter.DateConverter;

/**
 * @author 田平 create 2016年12月7日下午12:10:52
 */
public class CopyUtil {

	private static final String classPropName = "class";

	public static void copyMapToBean(Map<String, Object> map, Object bean) {
		if (bean != null && map != null) {
			try {
				ConvertUtils.register(DateConverter.getDateConverter(), Date.class);
				BeanUtils.populate(bean, map);
			} catch (Exception e) {
				throw new RuntimeException("copyMapToBean error!", e);
			}
		}
	}

	public static void copyMapToBean(List<String> excludeProps, Map<String, Object> properties, Object bean) {
		if ((bean == null) || (properties == null)) {
			return;
		}
		try {
			for (final Map.Entry<String, Object> entry : properties.entrySet()) {
				final String name = entry.getKey();
				if (name == null || excludeProps.contains(name)) {
					continue;
				}
				BeanUtilsBean.getInstance().setProperty(bean, name, entry.getValue());
			}
		} catch (Exception e) {
			throw new RuntimeException("copyMapToBean error!", e);
		}
	}

	public static void copyBeanToMap(Object bean, Map<String, Object> map) {
		copyBeanToMap(null, bean, map);
	}

	public static void copyBeanToMap(List<String> excludeProps, Object bean, Map<String, Object> map) {
		if (bean != null && map != null) {
			BeanWrapper beanWrapper = new BeanWrapperImpl(bean);
			PropertyDescriptor[] descriptor = beanWrapper.getPropertyDescriptors();
			for (int i = 0; i < descriptor.length; i++) {
				String name = descriptor[i].getName();
				if (classPropName.equals(name)) {
					continue;
				}
				if (ObjectUtils.isEmpty(excludeProps) || !excludeProps.contains(name)) {
					map.put(name, beanWrapper.getPropertyValue(name));
				}
			}
		}
	}
	
}
