package jp.ito.camera;

import android.hardware.Camera;
import android.content.Context;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.MotionEvent;
import android.os.Bundle;
import android.util.Log;
import android.hardware.Camera.Size;
import java.util.List;
import android.view.ViewGroup.LayoutParams;

public class CameraView extends SurfaceView implements SurfaceHolder.Callback{
	private static final String TAG = CameraView.class.getSimpleName();
	private	SurfaceHolder	_SurfaceHolder;
	public	Camera			_camera = null;

	private Camera getCamera(){
		while (true){
			if (_camera != null){
				return _camera;
			}
			try {
				Thread.sleep(300);
			} catch (InterruptedException e) {
			}
		}
	}
	
	public CameraView(Context context,Bundle savedInstanceState){
		super(context);
		Log.d(TAG, "CameraView()");

		_SurfaceHolder = getHolder();
		_SurfaceHolder.addCallback(this);
		_SurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
	}

	public void surfaceCreated(SurfaceHolder holder){
		Log.d(TAG, "surfaceCreated()");

		try{
			getCamera().setPreviewDisplay(holder);
		}
		catch (Exception e){
			Log.e(TAG, "surfaceCreated() : Fail to setPreviewDisplay.");
		}
	}

	public void surfaceChanged(SurfaceHolder holder,int format,int w,int h){
		Log.d(TAG, "surfaceChanged()");

		try {
			Camera camera = getCamera();
			camera.setPreviewCallback(null);		// 不要なはず再表示されないので
			camera.stopPreview();					// 不要なはず再表示されないので

			Camera.Parameters	paramCamera = camera.getParameters();
			List<Size>			asizeSupport;
			Size		size;

			asizeSupport = paramCamera.getSupportedPictureSizes();
			if(asizeSupport.size() != 0){
				size = asizeSupport.get(0);
				paramCamera.setPictureSize(size.width,size.height);
			}
			
			asizeSupport = paramCamera.getSupportedPreviewSizes();
			if(asizeSupport.size() != 0){
				size = asizeSupport.get(asizeSupport.size() - 1);
				paramCamera.setPreviewSize(size.width,size.height);
				LayoutParams	paramLayout;

				paramLayout = getLayoutParams();
				paramLayout.width = size.width;
				paramLayout.height = size.height;
				setLayoutParams(paramLayout);
			}
			camera.setParameters(paramCamera);
			camera.setPreviewDisplay(holder);		// 不要なはず再表示されないので
			camera.startPreview();
			invalidate();							// 不要なはず再表示されないので
		} catch (Exception e) {
			Log.e(TAG, "surfaceChanged()" + e);
		}
	}

	public void surfaceDestroyed(SurfaceHolder holder){
		Log.d(TAG, "surfaceDestroyed()");

	//	Camera camera = getCamera();
	//	camera.setPreviewCallback(null);
	//	camera.stopPreview();
	//	camera.release();
	//	camera = null;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event){
		if(event.getAction() == MotionEvent.ACTION_DOWN){
			Log.d(TAG, "onTouchEvent()");
//			TakePicture();
		}
		return true;
	}

}
