package gov.nasa.jpl.issm;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.DoubleBuffer;

import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

public class ImageResizer {

	private static DoubleBuffer buffer;

	public static Bitmap decodeSampledBitmapFromURL(URL url, int reqWidth,
			int reqHeight) {

		// First decode with inJustDecodeBounds=true to check dimensions
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		try {
			BitmapFactory.decodeStream(url.openConnection().getInputStream(),
					null, options);

			// Calculate inSampleSize
			options.inSampleSize = 1;

			// Decode bitmap with inSampleSize set
			options.inJustDecodeBounds = false;
			return BitmapFactory.decodeStream(url.openConnection()
					.getInputStream(), null, options);
		} catch (IOException e) {
			Log.e("Error", "Could not load Bitmap from: " + url.toString());
		}
		return null;
	}

	// public static Bitmap decodeSampledBitmapFromResource(Resources res, int
	// resId,
	// int reqWidth, int reqHeight) {
	//
	// // First decode with inJustDecodeBounds=true to check dimensions
	// final BitmapFactory.Options options = new BitmapFactory.Options();
	// options.inJustDecodeBounds = true;
	// BitmapFactory.decodeResource(res, resId, options);
	//
	// // Calculate inSampleSize
	// options.inSampleSize = calculateInSampleSize(options, reqWidth,
	// reqHeight);
	//
	// // Decode bitmap with inSampleSize set
	// options.inJustDecodeBounds = false;
	// return BitmapFactory.decodeResource(res, resId, options);
	// }

	public static Bitmap decodeSampledBitmapFromResource(Resources res,
			int resId, int reqWidth, int reqHeight) {
		// First decode with inJustDecodeBounds=true to check dimensions
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeResource(res, resId, options);

		// Calculate inSampleSize
		options.inSampleSize = calculateInSampleSize(options, reqWidth,
				reqHeight);

		// Decode bitmap with inSampleSize set
		options.inJustDecodeBounds = false;
		// buffer =
		// ByteBuffer.allocateDirect(options.outWidth*options.outHeight*4).order(ByteOrder.nativeOrder()).asDoubleBuffer();
		// Log.i("Buffer size: ", String.valueOf(buffer.capacity()));
		return BitmapFactory.decodeResource(res, resId, options);
	}

	public static Bitmap decodeSampledBitmapFromAsset(InputStream is,
			int reqWidth, int reqHeight) {
		byte[] byteArr = new byte[0];
		byte[] buffer = new byte[1024];
		int len;
		int count = 0;

		try {
			while ((len = is.read(buffer)) > -1) {
				if (len != 0) {
					if (count + len > byteArr.length) {
						byte[] newbuf = new byte[(count + len) * 2];
						System.arraycopy(byteArr, 0, newbuf, 0, count);
						byteArr = newbuf;
					}

					System.arraycopy(buffer, 0, byteArr, count, len);
					count += len;
				}
			}

			final BitmapFactory.Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = true;
			BitmapFactory.decodeByteArray(byteArr, 0, count, options);

			options.inSampleSize = calculateInSampleSize(options, reqWidth,
					reqHeight);
			options.inPurgeable = true;
			options.inInputShareable = true;
			options.inJustDecodeBounds = false;
			options.inPreferredConfig = Bitmap.Config.ARGB_8888;

			return BitmapFactory.decodeByteArray(byteArr, 0, count, options);

		} catch (Exception e) {
			e.printStackTrace();

			return null;
		}
	}

	// public static Bitmap decodeSampledBitmapFromAsset(InputStream is,
	// int reqWidth, int reqHeight) {
	// return BitmapFactory.decodeStream(is);
	// }

	public static int calculateInSampleSize(BitmapFactory.Options options,
			int reqWidth, int reqHeight) {
		// Raw height and width of image
		int height = options.outHeight;
		int width = options.outWidth;
		// Log.i("pic width: ", String.valueOf(width));
		// Log.i("pic height: ", String.valueOf(height));
		int inSampleSize = 1;

		if (height > reqHeight || width > reqWidth) {

			// Calculate ratios of height and width to requested height and
			// width
			final int heightRatio = Math.round((float) height
					/ (float) reqHeight);
			final int widthRatio = Math.round((float) width / (float) reqWidth);
			// Log.i("width ratio: ", String.valueOf(widthRatio));
			// Log.i("height ratio: ", String.valueOf(heightRatio));

			// Choose the smallest ratio as inSampleSize value, this will
			// guarantee
			// a final image with both dimensions larger than or equal to the
			// requested height and width.
			inSampleSize = heightRatio > widthRatio ? heightRatio : widthRatio;
			inSampleSize = (int) Math
					.pow(2, Math.floor(Math.log(inSampleSize)));
			// Log.i("sample size: ", String.valueOf(inSampleSize));
		}

		return inSampleSize;

	}

}
