package com.emegasoft.honeywellscan;

import java.io.IOException;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import anywheresoftware.b4a.BA.ActivityObject;
import anywheresoftware.b4a.BA.Hide;
import anywheresoftware.b4a.keywords.Common;

import com.honeywell.decodemanager.DecodeManager;
import com.honeywell.decodemanager.SymbologyConfigs;
import com.honeywell.decodemanager.barcode.DecodeResult;
import com.honeywell.decodemanager.symbologyconfig.SymbologyConfigCode39;

@ActivityObject

@Hide
public class HoneywellScanMainActivity extends Activity {

//	private final int ID_SCANSETTING = 0x12;
//	private final int ID_CLEAR_SCREEN = 0x13;
	private final int SCANKEY        = 0x94;

	private DecodeManager mDecodeManager = null;
	//private EditText mDecodeResultEdit = null;
	//private final int SCANTIMEOUT = 2000;
	private int SCANTIMEOUT = 2000;
	
	long mScanAccount = 0;
	private boolean mbKeyDown = true;

	//private boolean hasSurface;

	// private String strResultM;
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		Common.Log("create activity");
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);

		initializeUI();
		
		SCANTIMEOUT = getIntent().getIntExtra("ScanTimeOut", 2000);
		Log.v("SCANTIMEOUT" + SCANTIMEOUT ,"SCANTIMEOUT" + SCANTIMEOUT );

	}

	@Override
	protected void onResume() {
		super.onResume();

		Log.v("init DecodeManager","init DecodeManager");
		
		if (mDecodeManager == null) {
			mDecodeManager = new DecodeManager(this,ScanResultHandler);
			//configureReader();
		}
		
	}

	@Override
	protected void onPause() {
		super.onPause();

		if (mDecodeManager != null) {
			try {
				mDecodeManager.release();
				mDecodeManager = null;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_ENTER:
				try {
					if (mbKeyDown) {
						DoScan();
						mbKeyDown = false;
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			return true;
		case KeyEvent.KEYCODE_BACK:
			this.finish();
			return true;
        case KeyEvent.KEYCODE_UNKNOWN:	
        	if(event.getScanCode() == SCANKEY || event.getScanCode() == 87 || event.getScanCode() == 88) {
				try {
					if (mbKeyDown) {
						DoScan();
						mbKeyDown = false;
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
        	}
        	return true;
		default:
			return super.onKeyDown(keyCode, event);
		}
	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_ENTER:
			try {
				mbKeyDown = true;
				cancleScan();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return true;
		case KeyEvent.KEYCODE_BACK:
			this.finish();
			return true;
			
        case KeyEvent.KEYCODE_UNKNOWN:	
        	if(event.getScanCode() == SCANKEY || event.getScanCode() == 87 || event.getScanCode() == 88) {
    			try {
    				mbKeyDown = true;
    				cancleScan();
    			} catch (Exception e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
        	}
        	return true;
		default:
			return super.onKeyUp(keyCode, event);
		}
	}

	
	private void initializeUI() {
		
		Log.v("initializeUI","initializeUI");
		
		final Button button = new Button(this);
		button.setBackgroundColor(Color.DKGRAY);
		button.setText("ESCANEAR");
		
		FrameLayout fl=new FrameLayout(this);
		FrameLayout.LayoutParams lps=new LayoutParams(-1, -1);
		lps.gravity=Gravity.CENTER;
		fl.setBackgroundColor(Color.WHITE);
		
		fl.addView (button,lps);
		setContentView(fl);

		
		button.setOnTouchListener(new Button.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				final int action = event.getAction();
				switch (action) {
				case MotionEvent.ACTION_DOWN:
						try {
							if (mbKeyDown) {
								DoScan();
								mbKeyDown = false;
							}
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					break;
				case MotionEvent.ACTION_UP:
					try {
						mbKeyDown = true;
						cancleScan();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					break;
				}
				return true;
			}
		});

		
	}

	/*
	private void configureReader(){
		
		SymbologyConfigCodeEan13 cfgEan13 = new SymbologyConfigCodeEan13();
		cfgEan13.enableSymbology(true);
		cfgEan13.enableCheckTransmit(true);

		SymbologyConfigCode39 cfgEan39 = new SymbologyConfigCode39();
		cfgEan39.enableSymbology(true);
		cfgEan39.enableCheckTransmit(true);
		

		SymbologyConfigs symconfig = new SymbologyConfigs();

		symconfig.addSymbologyConfig(cfgEan13);
		symconfig.addSymbologyConfig(cfgEan39);
		
		try {
			mDecodeManager.setSymbologyConfigs(symconfig);
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	*/
	
	/*
	private void DoScan2(){
		Toast.makeText(this, "hola", Toast.LENGTH_LONG);
	
		Intent data=new Intent();
		data.putExtra("value", "codigo de barras");
		setResult(RESULT_OK, data);
		//zx.Ret(obj.getBarcodeFormat().toString(),obj.getText(),barcode);
		//finish();

		
	}
	 */

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	private void DoScan() throws Exception {
		try {
			Log.v("mDecodeManager.doDecode(SCANTIMEOUT);","mDecodeManager.doDecode(SCANTIMEOUT);");
			
			if (SCANTIMEOUT==0){
				
				mDecodeManager.getSymConfigActivityOpeartor().start();
			}
			else{
				mDecodeManager.doDecode(SCANTIMEOUT);
			}
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private Handler ScanResultHandler = new Handler() {
		public void handleMessage(Message msg) {
			Log.v("handleMessage","handleMessage");

			switch (msg.what) {
			case DecodeManager.MESSAGE_DECODER_COMPLETE:
				mScanAccount++;
				String strDecodeResult = "";
				DecodeResult decodeResult = (DecodeResult) msg.obj;

		
				byte codeid = decodeResult.codeId;
				byte aimid = decodeResult.aimId;
				int iLength = decodeResult.length;

				strDecodeResult = "Decode Result::"+ decodeResult.barcodeData + "\r\n" + "codeid::"+ "(" + String.valueOf((char) codeid) +"/"+  String.valueOf((char) aimid)+")" + "\r\n" + "Length:: " + iLength
						+ "  " + "Count:: " + mScanAccount + "\r\n";
				
				//mDecodeResultEdit.setText(strDecodeResult);
				
				Log.i("B4A", strDecodeResult);
				Intent data=new Intent();
				data.putExtra("value", decodeResult.barcodeData);
				
				setResult(RESULT_OK, data);
				//zx.Ret(obj.getBarcodeFormat().toString(),obj.getText(),barcode);
				finish();
				
				
				
				break;

			case DecodeManager.MESSAGE_DECODER_FAIL: {
				
				//mDecodeResultEdit.setText("Decode Result::Scan fail");
				Intent data2=new Intent();
				data2.putExtra("value", "Scan Fail");
				setResult(RESULT_OK, data2);
				//zx.Ret(obj.getBarcodeFormat().toString(),obj.getText(),barcode);
				finish();

			}
			break;
			case DecodeManager.MESSAGE_DECODER_READY:
			{
				try {
					//mDecodeManager.disableSymbology(CommonDefine.SymbologyID.SYM_ALL);
					SymbologyConfigCode39 code39 = new SymbologyConfigCode39();
					code39.enableCheckEnable(false);
					code39.enableSymbology(false);
					code39.setMaxLength(48);
					code39.setMinLength(2);
					
					SymbologyConfigs symconfig = new SymbologyConfigs();

					symconfig.addSymbologyConfig(code39);
									
					mDecodeManager.setSymbologyConfigs(symconfig);
				
				} catch (RemoteException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			break;
			default:
				super.handleMessage(msg);
				break;
			}
		}
	};

	private void cancleScan() throws Exception {
		mDecodeManager.cancelDecode();
	}
	
	
	
	
}