package com.cku.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;

import com.cku.core.RESTResponse;

import net.sf.json.JSONObject;

public class StreamUtils
{
	public static String readStringFromInputStream(int length, InputStream s) throws IOException
	{
		if (length >= 0)
		{
			byte[] bytes = new byte[length];
			
			int read = 0;
			while (true)
			{
				int r = s.read(bytes, read, bytes.length - read);
				read += r;
				if (read == length)
				{
					break;
				}				
			}			
	
			String str = new String(bytes, "utf-8");
			return str;
		}
		else
		{
			ByteArrayOutputStream bo = new ByteArrayOutputStream();
			while (true)
			{
				byte[] bytes = new byte[1 << 10];
				int read = s.read(bytes);
				if (read == -1) break;
				
				bo.write(bytes);
			}

			String str = new String(bo.toByteArray(), "utf-8");
			return str;
		}
	}
	
	public static JSONObject readJSONFromInputStream(int length, InputStream s) throws IOException
	{
		String str = readStringFromInputStream(length, s);
		return JSONObject.fromObject(str);
	}

	public static void writeStream(OutputStream s, RESTResponse r) throws IOException
	{
		JSONObject jObject = new JSONObject();
		
		jObject.put("rc", r.getRc());
		jObject.put("msg", r.getMsg());
		jObject.put("src", r.getSrc());
		
		JSONObject data = r.getData();
		if (data != null)
		{
			for (Object key : data.keySet())
			{
				Object val = data.get(key);
				jObject.put(key, val);
			}
		}
		
		String str = jObject.toString();
		s.write(str.getBytes(Charset.forName("utf-8")));
	}
}
