package com.qiyou.mb.android.utils.image;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.LinkedList;
import java.util.List;

import com.qiyou.mb.android.utils.log.QLog;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;

public class ImageUtil {
	public static final String TAG = "com.qiyou.mb.android.utils.ImageUtil";
	public static final String dTAG = "com.qiyou";
	@SuppressLint("NewApi")
	public static Bitmap get_Picture_bitmap(String imagePath) {

	    long size_file = getFileSize(new File(imagePath));

	    size_file = (size_file) / 1000;// in Kb now
	    int ample_size = 1;

	    if (size_file <= 250) {

	        System.out.println("SSSSS1111= " + size_file);
	        ample_size = 2;

	    } else if (size_file > 251 && size_file < 1500) {

	        System.out.println("SSSSS2222= " + size_file);
	        ample_size = 4;

	    } else if (size_file >= 1500 && size_file < 3000) {

	        System.out.println("SSSSS3333= " + size_file);
	        ample_size = 8;

	    } else if (size_file >= 3000 && size_file <= 4500) {

	        System.out.println("SSSSS4444= " + size_file);
	        ample_size = 12;

	    } else if (size_file >= 4500) {

	        System.out.println("SSSSS4444= " + size_file);
	        ample_size = 16;
	    }

	    Bitmap bitmap = null;

	    BitmapFactory.Options bitoption = new BitmapFactory.Options();
	    bitoption.inSampleSize = ample_size;

	    Bitmap bitmapPhoto = BitmapFactory.decodeFile(imagePath, bitoption);

	    ExifInterface exif = null;
	    try {
	        exif = new ExifInterface(imagePath);
	    } catch (IOException e) {
	        // Auto-generated catch block
	        e.printStackTrace();
	    }
	    int orientation = exif
	            .getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
	    Matrix matrix = new Matrix();

	    if ((orientation == 3)) {
	        matrix.postRotate(180);
	        bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0,
	                bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix,
	                true);

	    } else if (orientation == 6) {
	        matrix.postRotate(90);
	        bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0,
	                bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix,
	                true);

	    } else if (orientation == 8) {
	        matrix.postRotate(270);
	        bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0,
	                bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix,
	                true);

	    } else {
	        matrix.postRotate(0);
	        bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0,
	                bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix,
	                true);

	    }

	    return bitmap;

	}
	public static long getFileSize(final File file) {
	    if (file == null || !file.exists())
	        return 0;
	    if (!file.isDirectory())
	        return file.length();
	    final List<File> dirs = new LinkedList<File>();
	    dirs.add(file);
	    long result = 0;
	    while (!dirs.isEmpty()) {
	        final File dir = dirs.remove(0);
	        if (!dir.exists())
	            continue;
	        final File[] listFiles = dir.listFiles();
	        if (listFiles == null || listFiles.length == 0)
	            continue;
	        for (final File child : listFiles) {
	            result += child.length();
	            if (child.isDirectory())
	                dirs.add(child);
	        }
	    }

	    return result;
	}
	 
	/**
	 * Calcuate how much to compress the image
	 * @param options
	 * @param reqWidth
	 * @param reqHeight
	 * @return
	 */
	public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth) {
	// Raw height and width of image
	final int height = options.outHeight;
	final int width = options.outWidth;
    int reqHeight = (int) (height * reqWidth / (double) width); // casts to avoid truncating

	int inSampleSize = 1;

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

	    final int halfHeight = height / 2;
	    final int halfWidth = width / 2;

	    // Calculate the largest inSampleSize value that is a power of 2 and keeps both
	    // height and width larger than the requested height and width.
	    while ((halfHeight / inSampleSize) > reqHeight
	            && (halfWidth / inSampleSize) > reqWidth) {
	        inSampleSize *= 2;
	    }
	}

	return inSampleSize;
	}

	/**
	 * resize image to 480x800
	 * @param filePath
	 * @return
	 */
	@SuppressLint("NewApi")
	public static Bitmap getSmallBitmap(String filePath, int targetWidth) {

	    File file = new File(filePath);
	    long originalSize = file.length();
//	    int targetWidth = 640; // your arbitrary fixed limit

 	     QLog.getLogger().d(dTAG,TAG+"Original image size is: " + originalSize + " bytes.");

	    final BitmapFactory.Options options = new BitmapFactory.Options();
	    options.inJustDecodeBounds = true;
	    BitmapFactory.decodeFile(filePath, options);

	    // Calculate inSampleSize based on a preset ratio
	    options.inSampleSize = calculateInSampleSize(options, targetWidth);

	    // Decode bitmap with inSampleSize set
	    options.inJustDecodeBounds = false;

	    Bitmap compressedImage = BitmapFactory.decodeFile(filePath, options);

	   /* OutputStream imagefile = new FileOutputStream("/your/file/name.jpg");
	 // Write 'bitmap' to file using JPEG and 80% quality hint for JPEG:
	 bitmap.compress(CompressFormat.JPEG, 80, imagefile);*/
	    getCorrectDirection(filePath,compressedImage);
         QLog.getLogger().d(dTAG,TAG+" Compressed image size is " +  compressedImage.getByteCount() + " bytes, percent:" + (compressedImage.getByteCount()*100/originalSize));
	    

	    return compressedImage;
	}
	
	@SuppressLint("NewApi")
	static Bitmap getCorrectDirection(String imagePath,Bitmap bitmapPhoto ){
		
		if (bitmapPhoto == null){
			return null;
		}
		
		ExifInterface exif = null;
		Bitmap bitmap =bitmapPhoto;
	    try {
	        exif = new ExifInterface(imagePath);
	    } catch (IOException e) {
	        // Auto-generated catch block
	        e.printStackTrace();
	    }
	    int orientation = exif
	            .getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
	    Matrix matrix = new Matrix();

	    if ((orientation == 3)) {
	        matrix.postRotate(180);
	        bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0,
	                bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix,
	                true);

	    } else if (orientation == 6) {
	        matrix.postRotate(90);
	        bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0,
	                bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix,
	                true);

	    } else if (orientation == 8) {
	        matrix.postRotate(270);
	        bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0,
	                bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix,
	                true);

	    } else {
	        matrix.postRotate(0);
	        bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0,
	                bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix,
	                true);

	    }

	    return bitmap;
	}
	static Bitmap rotateImage(Bitmap bitmapPhoto,int degree ){
	  
	    Matrix matrix = new Matrix();
	    matrix.postRotate(degree);
	    Bitmap bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0,
                bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix,
                true);
        
	     
	    return bitmap;
	}
}
