package cn.pluss.platform.leshua;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.thoughtworks.xstream.XStream;

/**
 * @author yuchen
 *
 * @Description 
 */
public class LeshuaUtils {
	
	 //打log用
    private static Logger logger = LoggerFactory.getLogger(LeshuaUtils.class);
    
	public static byte[] readInput(InputStream in) throws IOException {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int len = 0;
		byte[] buffer = new byte[1024];
		try {
			while ((len = in.read(buffer)) > 0) {
				out.write(buffer, 0, len);
			}
		} finally {
			out.close();
			in.close();
		}
		return out.toByteArray();
	}

    public static String inputStreamToString(InputStream is) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int i;
        while ((i = is.read()) != -1) {
            baos.write(i);
        }
        return baos.toString("UTF-8");
    }


    public static InputStream getStringStream(String sInputString) throws UnsupportedEncodingException {
        ByteArrayInputStream tInputStringStream = null;
        if (sInputString != null && !sInputString.trim().equals("")) {
            tInputStringStream = new ByteArrayInputStream(sInputString.getBytes("UTF-8"));
        }
        return tInputStringStream;
    }

    public static Object getObjectFromXML(String xml, Class<?> tClass) {
       return getObjectFromXML(xml, tClass, "xml");
    }
    
    public static Object getObjectFromXML(String xml, Class<?> tClass, String alias) {
        //将从API返回的XML数据映射到Java对象
        XStream xStreamForResponseData = new XStream();
        XStream.setupDefaultSecurity(xStreamForResponseData);  
        xStreamForResponseData.alias(alias, tClass);
        xStreamForResponseData.allowTypes(new Class[]{tClass});
        xStreamForResponseData.ignoreUnknownElements();//暂时忽略掉一些新增的字段
        return xStreamForResponseData.fromXML(xml);
    }
    
    /**
     * 将对象转换成map，key为属性名，value为属性值，值为null的属性排除
     * @param obj
     * @return
     * @throws SecurityException 
     * @throws NoSuchMethodException 
     * @throws InvocationTargetException 
     */
	public static Map<String, String> toMap(Object obj) throws InvocationTargetException, NoSuchMethodException, SecurityException {
		Map<String, String> map = new HashMap<String,String>();

		Field[] fields = obj.getClass().getDeclaredFields(); //获取当前类的所有属性值（不包括继承的属性）
		for (Field field : fields) {
			try {
				Object val = queryFieldValue(obj,field);
				if (val != null) {
					map.put(field.getName(), String.valueOf(val));
				}
			} catch (IllegalArgumentException e) {
				logger.error(e.getMessage(), e);
			} catch (IllegalAccessException e) {
				logger.error(e.getMessage(), e);
			}
		}
		Field[] parentFields = obj.getClass().getFields();//获取类的所有public属性（包括继承的属性，这里的用处就是获取到所有父类的属性值）
		for (Field field : parentFields) {
			try {
				Object val = field.get(obj);
				if (val != null) {
					map.put(field.getName(), String.valueOf(val));
				}
			} catch (IllegalArgumentException e) {
				logger.error(e.getMessage(), e);
			} catch (IllegalAccessException e) {
				logger.error(e.getMessage(), e);
			}
		}
		return map;
	}
	
	/**
	 * 获取属性值
	 * @param object
	 * @param field
	 * @return
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 * @throws InvocationTargetException
	 * @throws NoSuchMethodException
	 * @throws SecurityException
	 */
	public static Object queryFieldValue(Object object,Field field) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException{
		String xString="get" + field.getName().substring(0, 1).toUpperCase()+ field.getName().substring(1);
		System.out.println(xString);
		 xString="get" + field.getName().substring(0, 1).toUpperCase()+ field.getName().substring(2);
		 System.out.println(xString);
		 xString="get" + field.getName().substring(0, 2).toUpperCase()+ field.getName().substring(1);
		System.out.println(xString);
		xString="get" + field.getName().substring(1, 2).toUpperCase()+ field.getName().substring(1);
		System.out.println(xString);
		xString="get" + field.getName().substring(1, 2).toUpperCase()+ field.getName().substring(1);
		System.out.println(xString);
		Method method = object.getClass().getMethod(
				"get" + field.getName().substring(0, 1).toUpperCase()
						+ field.getName().substring(1));
		if (method != null) {
			Object value = method.invoke(object);
			return value;
		} 			
		return null;
	}
	
	/**
	 * 计算失效时间
	 * @param now
	 * @param expireInMinutes
	 * @param dateFormat
	 * @return
	 */
	public static String calcExpireTime(Date now, String expireInMinutes, SimpleDateFormat dateFormat) {
		return dateFormat.format(now.getTime() + Long.parseLong(expireInMinutes) * 60 * 1000);
	}

}

