package r.e;
//propbridge camera image helper pseudoservice
//Lets you send files or strings out by basic protocols (FTP, email, sms)
//Likely to include more commandline "things" later on
//TODO: Turn this into a secondary activity, primary should be a revamp of the propbridge terminal

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

import re.anywhere.client.ExecByBatch;


import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class c extends Activity implements SurfaceHolder.Callback {
	static final int FOTO_MODE = 0;
	private static final String TAG = "CameraTest";
	Camera mCamera;
	public c soliton = this;
	boolean mPreviewRunning = false;
	private Context mContext = this;
	public static Bundle bundle;

	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);

		
		Log.e(TAG, "onCreate");

		bundle = getIntent().getExtras(); // used to decide parameters, file/email, etc.

		//		getWindow().setFormat(PixelFormat.TRANSLUCENT);
		//		requestWindowFeature(Window.FEATURE_NO_TITLE);
		//		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.camera);
		mSurfaceView = (SurfaceView) findViewById(R.id.surface_camera);
		mSurfaceHolder = mSurfaceView.getHolder();
		mSurfaceHolder.addCallback(this);
		mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
	}

	
	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
	}



	Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() {
		public void onPictureTaken(byte[] imageData, Camera c) {

			if (imageData != null) {
				StoreByteImage(mContext, imageData, 50,
						"ImageName");
				finish(); // close the app
			}
		}
	};


	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}

	protected void onStop() {
		Log.e(TAG, "onStop");
		super.onStop();
	}

	public void surfaceCreated(SurfaceHolder holder) {
		Log.e(TAG, "surfaceCreated");
		mCamera = Camera.open();
	}

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

		// XXX stopPreview() will crash if preview is not running
		if (mPreviewRunning) {
			mCamera.stopPreview();
		}

		try {
			Camera.Parameters p = mCamera.getParameters();
			p.setPreviewSize(w, h);
			mCamera.setParameters(p);
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			mCamera.setPreviewDisplay(holder);
			mCamera.startPreview();
			mPreviewRunning = true;
			SystemClock.sleep(2000); // give time for the ccd to initialize
			mCamera.takePicture(null, mPictureCallback, mPictureCallback);
		} catch (Exception e) {
			e.printStackTrace();
			CommandListServ.nuketheapp();
		}
	}

	public void surfaceDestroyed(SurfaceHolder holder) {
		/*
		try{
			Log.e(TAG, "surfaceDestroyed");
		mCamera.stopPreview();
		mPreviewRunning = false;
		mCamera.release();
		}catch(Exception e){e.printStackTrace();};
		*/
	}

	private SurfaceView mSurfaceView;
	private SurfaceHolder mSurfaceHolder;

	public boolean StoreByteImage(Context mContext, byte[] imageData,
			int quality, String expName) {

		FileOutputStream fileOutputStream = null;
		try {

			BitmapFactory.Options options=new BitmapFactory.Options();
			options.inSampleSize = 5;

			Bitmap myImage = BitmapFactory.decodeByteArray(imageData, 0,
					imageData.length,options);

			fileOutputStream = new FileOutputStream(getCacheDir().getAbsolutePath()+"/tempimage.jpg");
//			Log.e("DARP",""+getCacheDir().getAbsolutePath()+"/tempimage.jpg");
			//			fileOutputStream = new FileOutputStream("/data/local/image.jpg");

			BufferedOutputStream bos = new BufferedOutputStream(
					fileOutputStream);

			myImage.compress(CompressFormat.JPEG, quality, bos);

			bos.flush();
			bos.close();
			mCamera.stopPreview();
			mPreviewRunning = false;
			mCamera.release();
			//this.moveTaskToBack(true);
			DecideWhatToDoWithFile(getCacheDir().getAbsolutePath()+"/tempimage.jpg");
			//CommandList.nuketheapp();

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return true;
	}

	

	public void DecideWhatToDoWithFile(final String fileloc) { // if nothing is done, it just gets saved to the temp dir.

		ExecByBatch.RunQuick("toolbox chmod 666 "+fileloc);


		if (bundle!=null && bundle.isEmpty()==false)
		{

			if (bundle.containsKey("FTP")) //  ftp upload (overwrites)
			{
				final String[] parameters = bundle.getString("FTP").split(":");
				if (parameters.length==4)
					  new Thread(new Runnable() {
						    public void run() {
								CommandListServ.ftpsend(parameters[0],parameters[1],parameters[2],parameters[3],fileloc,false);
						    }
						  }).start();
			}
			if (bundle.containsKey("FTPW")) //  ftp upload (overwrites)
			{
				final String[] parameters = bundle.getString("FTPW").split(":");
				if (parameters.length==4)
					  new Thread(new Runnable() {
						    public void run() {
								CommandListServ.ftpsend(parameters[0],parameters[1],parameters[2],parameters[3],fileloc,false);
						    }
						  }).start();
			}

			if (bundle.containsKey("EMAIL")) // send an email
			{
				final String[] parameters = bundle.getString("EMAIL").split(":");
				if (parameters.length==5)
					  new Thread(new Runnable() {
						    public void run() {
								CommandListServ.sendemail(parameters[0],parameters[1],parameters[2],parameters[3],parameters[4],fileloc);
						    }
						  }).start();
			}
			if (bundle.containsKey("SAVE")) //  save locally
			{
				// for consistency this should go in commandlist and be made more robust...
					ExecByBatch.RunQuick("toolbox mv "+fileloc+" "+bundle.getString("SAVE"));
			}

		}
//		ExecByBatch.RunQuick("toolbox mv "+fileloc+" /data/local/PB_IMG.JPG"); // keep it

	}

}