package com.example.sagivtechtemplate;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

//OpenCV related imports.
import org.opencv.utils.*;
import org.opencv.android.*;
import org.opencv.core.*;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewListener;
import org.opencv.highgui.Highgui;
import org.opencv.imgproc.Imgproc;


public class SagivTechMainActivity extends Activity implements CvCameraViewListener, Handler.Callback {
    private final static String TAG = "SagivTechMainActivity";
    private ImageView ivResult_;
    private Mat matResult = null;
    private int h_ = 360;
    private int w_ = 480 * 2;  // * 2 since it shows both input and output side by side.
    private boolean bInitialized_ = false;
    public Handler mainHandler;
    private SagivTechProcessingThread sagivTechProcessingThread_ = null;
    private CameraBridgeViewBase  mOpenCvCameraView_ = null;

    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sagiv_tech_main);

		ivResult_ = (ImageView)findViewById(R.id.ivResult);
        mOpenCvCameraView_ = (CameraBridgeViewBase) findViewById(R.id.camera_view);
        mOpenCvCameraView_.setCvCameraViewListener(this);
    }

	private void initialize() {
		// Register thyself as a message handler.
		mainHandler = new Handler(this);
		// Initialize the processing thread.
		sagivTechProcessingThread_ = new SagivTechProcessingThread(this, h_, w_);
		sagivTechProcessingThread_.start();
        bInitialized_ = true;
	}
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.sagiv_tech_main, menu);
        return true;
    }

    // Load the OpenCV infra.
    private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
            @Override
            public void onManagerConnected(int status) {
                switch (status) {
                        case LoaderCallbackInterface.SUCCESS:
                        {
                        	// Enable the camera view.
                    		mOpenCvCameraView_.enableView();
                            Log.i(TAG, "OpenCV loaded successfully");
                            
                            // Load the native library.
                            Log.i(TAG, "Loading native library");
                            System.loadLibrary("SagivTechNative");
                            Log.i(TAG, "Native library loaded");
                            
                            // Initialize the processing thread.
                            initialize();
                            
                        } break;
                        default:
                        {
                            super.onManagerConnected(status);
                        } break;
                }
            }
        };
        
        @Override
        public void onPause()
        {
            super.onPause();
            if (mOpenCvCameraView_ != null)
                mOpenCvCameraView_.disableView();
        }

        @Override
        public void onResume()
        {
            super.onResume();
            OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_5, this, mLoaderCallback);
        }
        
        public void onDestroy() {
            super.onDestroy();
            if (mOpenCvCameraView_ != null)
                mOpenCvCameraView_.disableView();
        }        
        
        // CvCameraViewListner interface implementation.
        @Override
        public void onCameraViewStarted(int width, int height) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onCameraViewStopped() {
            // TODO Auto-generated method stub
        }

        @Override
        public Mat onCameraFrame(Mat inputFrame) {
        	if (!bInitialized_)
        		return inputFrame;
        	
        	sagivTechProcessingThread_.pushFrame(inputFrame);
            return inputFrame;
        }
        
        public void runOpenCVTest(View v) {
        	Log.v(TAG, "runOpenCVTest");
        	sagivTechProcessingThread_.bRunOpenCV_ = true;
        	sagivTechProcessingThread_.bRunOpenCL_ = false;
    		sagivTechProcessingThread_.bRun_ = true;
        }

        public void runOpenCLTest(View v) {
        	Log.v(TAG, "runOpenCLTest");
        	sagivTechProcessingThread_.bRunOpenCL_ = true;
        	sagivTechProcessingThread_.bRunOpenCV_ = false;
    		sagivTechProcessingThread_.bRun_ = true;
        }
        
    	private void displayResult(Mat matOutput) {
    		if ((null == matOutput) || (!bInitialized_))
    			return;
    		if ((0 == matOutput.rows()) || (0 == matOutput.cols()))
    			return;
    		
    		Bitmap bmpSource = Bitmap.createBitmap(matOutput.cols(),matOutput.rows(), Bitmap.Config.RGB_565);
    		//Bitmap bmpSource = Bitmap.createBitmap(matOutput.cols(),matOutput.rows(), Bitmap.Config.ARGB_8888);
    		Utils.matToBitmap(matOutput, bmpSource);
    		ivResult_.setImageBitmap(bmpSource);
    	}
        
        
        @Override
        public boolean handleMessage(Message msg) {
        	int err = msg.what;
        	if(err < 0)
        		Toast.makeText(getBaseContext(), "Error: " + err, Toast.LENGTH_SHORT).show();
        	Log.d(TAG, "Inisde handleMessage.");
        	if (null != sagivTechProcessingThread_) {

        		Mat matOutput =  null;
        		
        		synchronized(this) {
        			matOutput = (Mat)msg.obj;
        			displayResult(matOutput);
        		}
        	}
        	return true;
        }		
}

Legal Disclaimer:

You understand that when using the Site you may be exposed to content from a variety of sources, and that SagivTech is not responsible for the accuracy, usefulness, safety or intellectual property rights of, or relating to, such content and that such content does not express SagivTech’s opinion or endorsement of any subject matter and should not be relied upon as such. SagivTech and its affiliates accept no responsibility for any consequences whatsoever arising from use of such content. You acknowledge that any use of the content is at your own risk.