package com.jiebao.h518.scan;


import android.app.Activity;
import android.util.Log;
import com.motorolasolutions.adc.decoder.BarCodeReader;


public class DiemensionalCodeControler implements BarCodeReader.DecodeCallback {
	public interface DiemensionalScanListener{
		public void onDiemensionalScanComplete(String result,String error);
	}
	static final int STATE_IDLE = 0;
	static final int STATE_DECODE = 1;
	static final int STATE_HANDSFREE = 2;
	//static final int STATE_PREVIEW = 3; // snapshot preview mode
	//static final int STATE_SNAPSHOT = 4;
	//static final int STATE_VIDEO = 5;
	private BarCodeReader bcr;
//	private SqliteService sqlite;
	private Activity context;
	//private ToneGenerator tg = null;
	//private SoundPool soundpool = null;
	private int trigMode = BarCodeReader.ParamVal.LEVEL;
	private int state = STATE_IDLE;
	private int soundid;
	private BeepManager beepManager;
	private DiemensionalScanListener scanListener;
	private static DiemensionalCodeControler controler;
	static {
		System.loadLibrary("IAL");
		System.loadLibrary("SDL");
		System.loadLibrary("barcodereader");
	}

	private DiemensionalCodeControler(Activity context,DiemensionalScanListener scanListener) {
		open();
		this.context=context;
		this.scanListener=scanListener;
//		sqlite = new SqliteService(context);
//		if(sqlite.getCount() == 0){
//			sqlite.initCodeTpye();
//		}
		beepManager=new BeepManager(context);
	
	}
	/**
	 * 在程序退出时调用
	 */
	public static void setDiemensionalConNull(){
		if(controler!=null){
			controler.setIdle();
			controler.release();
			controler=null;
		}
	}
	public static DiemensionalCodeControler getCodeControler(Activity context,DiemensionalScanListener scanListener) {
		if (controler == null) {
			controler = new DiemensionalCodeControler(context,scanListener);
		}
		return controler;
	}
	private void beep() {
		playSound();
	}
	private synchronized void playSound() {
	
			beepManager.playBeepSoundAndVibrate();
		

	}
	public void open() {
		

		if (bcr == null) {
			try {
				bcr = BarCodeReader.open(1);
				if(bcr!=null)
				bcr.setDecodeCallback(this);
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				throw new RuntimeException("device open failed");
			}
		}

	}

	private void release() {
		try {
			if(beepManager!=null)beepManager.release();
			beepManager=null;
			if (bcr != null)
				bcr.release();
			bcr = null;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

	}
	private int doSetParam(BarCodeReader bcr,int num, int val) {
		String s = "";
		
		int ret = bcr.setParameter(num, val);
		if (ret != BarCodeReader.BCR_ERROR) {
			if (num == BarCodeReader.ParamNum.PRIM_TRIG_MODE) {
				trigMode = val;
				if (val == BarCodeReader.ParamVal.HANDSFREE) {
					s = "HandsFree";
				} else if (val == BarCodeReader.ParamVal.AUTO_AIM) {
					s = "AutoAim";
					ret = bcr
							.startHandsFreeDecode(BarCodeReader.ParamVal.AUTO_AIM);
					if (ret != BarCodeReader.BCR_SUCCESS) {
						//dspErr("AUtoAIm start FAILED");
					}
				} else if (val == BarCodeReader.ParamVal.LEVEL) {
					s = "Level";
				}
			} else if (num == BarCodeReader.ParamNum.IMG_VIDEOVF) {
			//if (snapPreview = (val == 1))
				//	s = "SnapPreview";
			}
		} else{
			s = " FAILED (" + ret + ")";
		}
		//dspStat(":   Set #" + num + " to " + val + " " + s);
		return ret;
	}
	private int setIdle() {
		int prevState = state;
		int ret = prevState; // for states taking time to chg/end

		state = STATE_IDLE;
		switch (prevState) {
		case STATE_HANDSFREE:   //当前状态为自动扫描
			resetTrigger();		//取消自动扫描
			break;
		case STATE_DECODE:      //当前状态了正在扫描
			//dspStat("decode stopped");  
			bcr.stopDecode();    //取消扫描
			break;
		default:
			ret = STATE_IDLE;
		}
		return ret;
	}
	private void resetTrigger() {
		doSetParam(bcr,BarCodeReader.ParamNum.PRIM_TRIG_MODE,
				BarCodeReader.ParamVal.LEVEL);
		trigMode = BarCodeReader.ParamVal.LEVEL;
	}
	/**
	 * 启动连续扫描
	 * @return
	 */
	public boolean doHandsFree(){
		System.out.println("长按----------------------------------------");
		if (setIdle() != STATE_IDLE)
			return false;

		int ret = bcr.startHandsFreeDecode(BarCodeReader.ParamVal.HANDSFREE);
		System.out.println("长按----------------------------------------");
		//判断返回值ret 若不等于0 启动连续扫描失败
		if (ret != BarCodeReader.BCR_SUCCESS){
			return false;
			//dspStat("startHandFree FAILED");
		}else {
			trigMode = BarCodeReader.ParamVal.HANDSFREE;
			state = STATE_HANDSFREE; //状态为连续扫描
			return true;
			//dspStat("HandsFree decoding");
		}
	}
	private boolean doDecode() {
		if (setIdle() != STATE_IDLE)
			return false;

		state = STATE_DECODE;
		//dspData("");
	//	dspStat(R.string.decoding);
		bcr.startDecode(); // start decode (callback gets results)
		return true;
	}
	/**
	 * 启动一次性扫描
	 * @return
	 */
	public boolean start(){
		doSetParam(bcr,298, 1);
		doSetParam(bcr,306, 1);
		return doDecode();
	}
	/**
	 * 停止扫描，适应一次或连续
	 */
	public void stop(){
		if(state==STATE_DECODE)bcr.stopDecode();
		if(state==STATE_HANDSFREE)resetTrigger();
		state=STATE_IDLE;
	}
	public void onDecodeComplete(int symbology, int length, byte[] data,
			BarCodeReader reader) {
		// TODO Auto-generated method stub	
		if(state == STATE_DECODE){
			stop();
		}
		if (length > 0) {
			
			//if (isHandsFree() == false && isAutoAim() == false)
				//bcr.stopDecode();


			if (symbology == 0x99) // type 99?
			{
				symbology = data[0];
				int n = data[1];
				int s = 2;
				int d = 0;
				int len = 0;
				byte d99[] = new byte[data.length];
				for (int i = 0; i < n; ++i) {
					s += 2;
					len = data[s++];
					System.arraycopy(data, s, d99, d, len);
					s += len;
					d += len;
				}
				d99[d] = 0;
				data = d99;
			}
//			String codeType = sqlite.searchCode(symbology);
//			if(codeType == null || codeType.equals("") ){//未知条码 类型
//				//dspStat("[" + decodes + "] type: " + "unknown type" + " len: " + length);
//				scanListener.onDiemensionalScanComplete(null, "未知条码类型");
//				return;
//			}else{
//			//dspStat("[" + decodes + "] type: " + codeType + " len: " + length);
//			}
		//	dspData(byte2hex(data));							
			try{
			String Result = new String(data,"GB2312");
			scanListener.onDiemensionalScanComplete(Result, null);
			//dspData(isSettingCode(SDLguiActivity.this,Result));
			
			}catch(Exception e){
				Log.i("info", "excption == "+e.getMessage());
				scanListener.onDiemensionalScanComplete(null, "转码错误");
			} 
				beep();
		} else // no-decode
		{
			//dspData("");
			//根据length来判断当前状态
			switch (length) {
			
			case BarCodeReader.DECODE_STATUS_TIMEOUT:  //解码超时， 在指定的时间内没有扫到码
				//dspStat("decode timed out");
				scanListener.onDiemensionalScanComplete(null, "解码超时");
				break;

			case BarCodeReader.DECODE_STATUS_CANCELED:   //取消扫描
				//dspStat("decode cancelled");
				scanListener.onDiemensionalScanComplete(null, "取消扫描");
				break;

			case BarCodeReader.DECODE_STATUS_ERROR:    //扫描出错
			default:
			//	dspStat("decode failed");
				scanListener.onDiemensionalScanComplete(null, "扫描出错");
				break;
			}
		}

	}

	public void onEvent(int event, int info, byte[] data, BarCodeReader reader) {
		// TODO Auto-generated method stub

	}

}
