package com.pictc.utils;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;


public class StringUtils {
	
	private StringUtils() {
		super();
	}
	
	public static boolean isEmpty(String str) {
		if(str==null || "".equals(str.trim())) {
			return true;
		}
		return false;
	}
	
	public static boolean isNotEmpty(String str) {
		return !isEmpty(str);
	}
	
	public static String parseBytes(byte[] data,Charset charset) {
		return new String(data, charset);
	}
	
	
	public static String parseStream(InputStream in,Charset charset) throws IOException {
		return parseStream(new InputStreamReader(in, charset));
	}
	
	public static String parseStream(Reader reader) throws IOException {
		try {
			StringBuilder source = new StringBuilder();
			BufferedReader buffered = new BufferedReader(reader);
			String line = buffered.readLine();

			while (line != null) {
				source.append(line);
				source.append('\n');
				line = buffered.readLine();
			}
			return source.toString();
		} finally {
			IoUtils.closeQuietly(reader);
		}
	}
	
	
	public static byte[] toBytes(String str,Charset charset) {
		if(str==null) {
			return null;
		}
		return str.getBytes(charset);
	}
	
	
	public static InputStream toInputStream(String str,Charset charset) {
		return new ByteArrayInputStream(toBytes(str,charset));
	}
	
	/**
	 * 将驼峰命名的字符串转为下划线
	 * */
	public static String convertHump(String str) {
		StringBuilder result=new StringBuilder();
		char[] chars=str.toCharArray();
		for (int i = 0; i < chars.length; i++) {
			if(Character.isUpperCase(chars[i])) {
				if(i>0) {
					result.append('_');
				}
				result.append(Character.toLowerCase(chars[i]));
				continue;
			}
			result.append(chars[i]);
		}
		return result.toString();
	}
	
	public static String excludeEmpty(String val,String defVal) {
		if(isEmpty(val)) {
			return defVal;
		}
		return val;
	}

	public static String format(String str,Object... args) {
		if(str!=null && args !=null && args.length > 0) {
			for (int i = 0; i < args.length; i++) {
				Object item = args[i];
				str = str.replace("{"+i+"}",item!=null?item.toString():"");	
			}
		}
		return str;
	}
	
	public static String opt(String val,String defVal) {
		if(isEmpty(val)) {
			return defVal;
		}
		return val;
	}
	
	public static boolean eq(String val,String secondVal) {
		if(val==null && secondVal==null) {
			return true;
		}
		if(val!=null) {
			return val.equals(secondVal);
		}
		return secondVal.equals(val);
	}
	

}
