package com.gh.common.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class CropImageCustom extends RelativeLayout {

	private CropImageZoomView mZoomImageView;
	private CropImageBorderView mClipImageView;

	private int mHorizontalPadding = 20;

	public CropImageCustom(Context context, AttributeSet attrs) {
		super(context, attrs);

		mZoomImageView = new CropImageZoomView(context);
		mClipImageView = new CropImageBorderView(context);

		android.view.ViewGroup.LayoutParams lp = new LayoutParams(
				android.view.ViewGroup.LayoutParams.MATCH_PARENT,
				android.view.ViewGroup.LayoutParams.MATCH_PARENT);

		this.addView(mZoomImageView, lp);
		this.addView(mClipImageView, lp);

		// 计算padding的px
		mHorizontalPadding = (int) TypedValue.applyDimension(
				TypedValue.COMPLEX_UNIT_DIP, mHorizontalPadding, getResources()
						.getDisplayMetrics());
		mZoomImageView.setHorizontalPadding(mHorizontalPadding);
		mClipImageView.setHorizontalPadding(mHorizontalPadding);
	}

	/**
	 * 对外公布设置边距的方法,单位为dp
	 * 
	 * @param mHorizontalPadding
	 */
	public void setHorizontalPadding(int mHorizontalPadding) {
		this.mHorizontalPadding = mHorizontalPadding;
	}

	/**
	 * 裁切图片
	 * 
	 * @return
	 */
	public Bitmap clip() {
		return mZoomImageView.clip();
	}

	public boolean savePicture(String path) {
		Bitmap bitmap = mZoomImageView.clip();
		File file = new File(path);
		int quality = 80;
		do {
			try {
				BufferedOutputStream bos = new BufferedOutputStream(
						new FileOutputStream(file));
				bitmap.compress(Bitmap.CompressFormat.JPEG, quality, bos);
				bos.flush();
				bos.close();
			} catch (IOException e) {
				file.delete();
				e.printStackTrace();
				return false;
			}
			quality -= 10;
		} while (file.length() > 81920);
		return true;
	}

	public ImageView getCropImageZoomView() {
		return mZoomImageView;
	}

	public void setBitmap(Bitmap bitmap) {
		mZoomImageView.setImageBitmap(bitmap);
	}

}
