package com.andorid.MuliModeComdemo;

//import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

import com.andorid.MFR0311HID.R;
import com.gary.fingerprint.proto.FingerprintPacket;
//import com.gary.msr.hid.USBOp;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
//import android.graphics.BitmapFactory;
import android.graphics.Color;
//import android.graphics.ImageFormat;
//import android.graphics.Rect;
//import android.graphics.YuvImage;
import android.hardware.usb.UsbManager;
import android.os.AsyncTask;
import android.os.Bundle;
//import android.os.Handler;
//import android.os.Looper;
//import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
//import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
//import android.widget.Toast;

public class Finger_DEV extends Activity implements OnClickListener{
	
	//Button fm5_GetImage;
	//Button fm5_UpImage;
	//Button fm5_GiveImage;
	Button fm5_Enroll;
	Button fm5_Verify;
	Button fm5_CancelOp;
	Button fm5_Opendev;
	Button fm5_Closedev;
	Button fm5_Quit;
	Button fm5_RefreshTable;
	Button fm5_DeleteID;
	Button fm5_ClearID;
	
	EditText fm5_fingerIDinput;
	
	ImageView fm5_fingerImage;
	
	ListView fm5_IDTable;
	TextView fm5_info;
	myTask mTask;
	myTaskVerify mTaskVerify;
	public static boolean myLoopStateFlag;  //是否用户主动退出循环
	public static String myInfonews; 
	public static int HID_VID = 0x10C4;
	public static int HID_PID = 0x8235;

	private String character[]={
				
    };
	private List<String> list = new ArrayList<String>();
	
//	private Handler handler;
	
	public static FingerprintPacket mFingerprintPacket;
	private static final String ACTION_USB_PERMISSION="com.andorid.MuliModeComdemo.USB_PERMISSION";
	ArrayAdapter<String> adapter;
	public static boolean goonflag;		//因为ID号已经存在用户是否点击了确定退出
	public static int EnrollIDIndex=0;
	public static int SearchIDindex=0; ///验证ID
	
	//ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, list);
	
	private class myTask extends AsyncTask<String, String, String>
	{
		protected void onPreExecute() {
			//
			fm5_info.setTextColor(Color.parseColor("#0000FF"));//显示蓝色
			fm5_info.setText("Place your fingers flat on the sensor"); //请放指头
	    }
		@Override
	    protected String doInBackground(String... params)
	    {
			int iRet,tmpIndex;
			for(tmpIndex=0;tmpIndex<4;tmpIndex++)
			{
				switch(tmpIndex)
				{
					case 0:
						myInfonews="Place your fingers flat on the sensor first time";
						publishProgress(myInfonews);
						break;
					case 1:
						myInfonews="Place your fingers flat on the sensor second time";
						publishProgress(myInfonews);
						break;
					case 2:
						myInfonews="Place your fingers flat on the sensor third time";
						publishProgress(myInfonews);
						break;
					case 3:
						myInfonews="Place your fingers flat on the sensor fourth time";
						publishProgress(myInfonews);
						break;
					default:
						break;
				
				}
				
				//获取图像
				while(true)
				{
					if(myLoopStateFlag==false)
					{
						myInfonews="Cancel operation";
						return myInfonews;
					}
					iRet=mFingerprintPacket.USB_PS_GetImage();
					if(iRet==0)//如果成功获取图像，跳出等待按指纹循环
                    {
                            break;
                    }
					try {
						Thread.sleep(1);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				
				//上传图像
				if(myLoopStateFlag==false)
				{
					myInfonews="Cancel operation";
					return myInfonews;
				}
				iRet=mFingerprintPacket.USB_PS_UpImage();
				if(iRet<0)
				{
					//publishProgress("");
					myInfonews="Uploading image failed";
					return myInfonews;	
				}
				else
				{
					myInfonews="UpImage Successful";
					publishProgress(myInfonews);	
				}
				if(myLoopStateFlag==false)
				{
					myInfonews="Cancel operation";
					return myInfonews;
				}
				iRet=mFingerprintPacket.USB_PS_GetChar(tmpIndex+1);//生成特征值
				if(iRet<0)
				{
					//publishProgress("");
					myInfonews="Uploading image failed";
					return myInfonews;	
				}
				///等待用户拿开手指
				myInfonews="Please take your finger off";
				publishProgress(myInfonews);
				while(true)
				{
					if(myLoopStateFlag==false)
					{
						myInfonews="Cancel operation";
						return myInfonews;
					}
					iRet=mFingerprintPacket.USB_PS_GetImage();
					if(iRet<0)//如果成功获取图像，跳出等待按指纹循环
                    {
                            break;
                    }
					try {
						Thread.sleep(1);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				
			}
			/////合并特征值,并保存
	        if(tmpIndex==4)
	        {
	        	//合并 并保存
	        	iRet=mFingerprintPacket.USB_PS_RegMB();
		        if(iRet<0)
	            {
	                    //StatusBar1->Panels->Items[1]->Text="录入指纹失败!";
		        	myInfonews="Enroll fingerprint failed ";
					return myInfonews;
	            }
		        iRet=mFingerprintPacket.USB_PS_StorMB(1,EnrollIDIndex);
		        if(iRet<0)
	            {
	                    //StatusBar1->Panels->Items[1]->Text="录入指纹失败!";
		        	myInfonews="Enroll fingerprint failed ";
					return myInfonews;
	            }
		        myInfonews="Enroll fingerprint successful";
	        }
			return myInfonews;
	    }
		
		protected void onProgressUpdate(String... progresses) {

	        //progressBar.setProgress(progresses[0]);
			fm5_info.setTextColor(Color.parseColor("#0000FF"));//显示蓝色
			fm5_info.setText(myInfonews);
			if(myInfonews.equals("UpImage Successful"))
			{
				
				Bitmap nbitmap=mFingerprintPacket.USB_PS_GiveImage();
				fm5_fingerImage.setImageBitmap(nbitmap);
			}
				
	    }
		protected void onPostExecute(String result) 
		{
			int i,j;
			fm5_info.setText(myInfonews);	
			onOpenButtonSetup();
			fm5_info.setTextColor(Color.parseColor("#FF0000"));//显示红色
			if(myInfonews.equals("Enroll fingerprint successful"))
			{
				fm5_info.setTextColor(Color.parseColor("#00FF00"));//显示绿色
				RefreshIDList();
				for(i=0;i<255;i++)
				{
					for(j=0;j<adapter.getCount();j++)
					{
						if(i==Integer.parseInt(adapter.getItem(j)))
							break;
					}
					if(j==adapter.getCount())
						break;
				}
				if(i>=100)
					i=0;
				fm5_fingerIDinput.setText(String.valueOf(i));
				
			}
				else if(myInfonews.equals("Cancel operation"))
				mFingerprintPacket.USB_PS_Cancel();
			else
			{}
		}
		protected void onCancelled()
		{
			
			fm5_info.setTextColor(Color.parseColor("#FF0000"));//显示红色
			fm5_info.setText("Cancel operation");
			onOpenButtonSetup();
			
		}
		
	}
	
	
	//////////////////验证指纹线程
	private class myTaskVerify extends AsyncTask<String, String, String>
	{
		protected void onPreExecute() {
			fm5_info.setTextColor(Color.parseColor("#0000FF"));//显示蓝色
			fm5_info.setText("Place your fingers flat on the sensor"); //请放指头
	    }
		@Override
	    protected String doInBackground(String... params)
	    {
			int iRet;//,tmpIndex;
			int []tmpBuf=new int[12];
				
				//获取图像
				while(true)
				{
					if(myLoopStateFlag==false)
					{
						myInfonews="Cancel operation";
						return myInfonews;
					}
					iRet=mFingerprintPacket.USB_PS_GetImage();
					if(iRet==0)//如果成功获取图像，跳出等待按指纹循环
                    {
                            break;
                    }
					try {
						Thread.sleep(1);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				
				if(myLoopStateFlag==false)
				{
					myInfonews="Cancel operation";
					return myInfonews;
				}
				iRet=mFingerprintPacket.USB_PS_GetChar(1);//生成特征值//此处固定为1
				if(iRet<0)
				{
					//publishProgress("");
					myInfonews="Verify fingerprint failed";
					return myInfonews;	
				}
				if(myLoopStateFlag==false)
				{
					myInfonews="Cancel operation";
					return myInfonews;
				}///
				//iRet=mFingerprintPacket.USB_PS_SearchMB(1,1,1,tmpBuf);//生成特征值
				iRet=mFingerprintPacket.USB_PS_SearchMB(1,1,99,tmpBuf);//生成特征值
				if(iRet<0)
				{
					//publishProgress("");
					myInfonews="Verify fingerprint failed";
					return myInfonews;	
				}
				SearchIDindex=tmpBuf[0]*256+tmpBuf[1];
				myInfonews="Verify fingerprint success";
				return myInfonews;
				
			
	    }
		
		protected void onProgressUpdate(String... progresses) {

	        //progressBar.setProgress(progresses[0]);
			fm5_info.setTextColor(Color.parseColor("#0000FF"));//显示蓝色
			fm5_info.setText(myInfonews);
				
	    }
		protected void onPostExecute(String result) 
		{
			fm5_info.setText(myInfonews);	
			onOpenButtonSetup();
			fm5_info.setTextColor(Color.parseColor("#FF0000"));//显示红色
			if(myInfonews.equals("Verify fingerprint success"))
			{
				fm5_info.setTextColor(Color.parseColor("#00FF00"));//显示绿色	
				String tmpStr="Verify fingerprint success ID = ";
					tmpStr=tmpStr+String.valueOf(SearchIDindex);
					fm5_info.setText(tmpStr);
				
			}
			else if(myInfonews.equals("Cancel operation"))
			{
				mFingerprintPacket.USB_PS_Cancel();
				fm5_info.setText(myInfonews);
			}
			else
			{
				fm5_info.setText(myInfonews);
			}
		}
		protected void onCancelled()
		{
			fm5_info.setTextColor(Color.parseColor("#FF0000"));//显示红色
			fm5_info.setText("Cancel operation");	
			onOpenButtonSetup();
		}
		
	}
	///刷新用户ID列表
	private void RefreshIDList()
	{
		int []tmpBuf=new int[64];
		byte tmpB;
		int tmpI;
		int iRet;
		adapter.clear();
		//fm5_IDTable.setAdapter(null);
		
		iRet=mFingerprintPacket.USB_PS_ReadIndexTable(0,tmpBuf);
		if(iRet!=0)
        {
                //ShowMessage("搜索指纹库失败");
                return ;
        }
		for(int j=0;j<32;j++)
		{
			//for(int k=0;k<32;k++)
			for(int k=0;k<8;k++)
			{
				tmpB=(byte)tmpBuf[j];
				//tmpB=0x0C;
				if((tmpB&(0x01<<k))!=0x00)
				{
					tmpI=j*8+k;
					//list.add(String.valueOf(tmpI));
					adapter.add(String.valueOf(tmpI));
					
				}
				
			}
			
		}
//		adapter.notifyDataSetChanged();
		if(adapter.getCount()>=1)
			fm5_IDTable.setItemChecked(0, true);

		adapter.notifyDataSetChanged();
		
		
		
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//USBOp.setVidAndPid(HID_VID, HID_PID);
		setContentView(R.layout.activity_finger__dev);
		
		
		//fm5_GetImage = (Button) findViewById(R.id.fmfinger_GetImage);
		//fm5_UpImage = (Button) findViewById(R.id.fmginger_UpImage);
		//fm5_GiveImage = (Button) findViewById(R.id.fmginger_GiveImage);
		
		fm5_Enroll = (Button) findViewById(R.id.fmfinger_Enroll);
		fm5_Verify = (Button) findViewById(R.id.fmfinger_Verify);
		fm5_CancelOp = (Button) findViewById(R.id.fmfinger_CancelOp);
		fm5_Opendev = (Button) findViewById(R.id.fmfinger_Opendev);
		fm5_Closedev = (Button) findViewById(R.id.fmfinger_Closedev);
		fm5_Quit = (Button) findViewById(R.id.fmfinger_Quit);
		fm5_RefreshTable = (Button) findViewById(R.id.fmfinger_RefreshTable);
		fm5_DeleteID = (Button) findViewById(R.id.fmfinger_DeleteID);
		fm5_ClearID = (Button) findViewById(R.id.fmfinger_ClearID);
		
		fm5_fingerImage=(ImageView)findViewById(R.id.fmginger_fingerImage);
		
		fm5_IDTable=(ListView)findViewById(R.id.fmfinger_IDTable);
		
		fm5_fingerIDinput=(EditText)findViewById(R.id.fmfinger_fingerIDinput);
		
		fm5_info=(TextView)findViewById(R.id.fmfinger_info);
		
		

		fm5_Enroll.setOnClickListener(this);
		fm5_Verify.setOnClickListener(this);
		fm5_CancelOp.setOnClickListener(this);
		fm5_Opendev.setOnClickListener(this);
		fm5_Closedev.setOnClickListener(this);
		fm5_Quit.setOnClickListener(this);
		fm5_RefreshTable.setOnClickListener(this);
		fm5_DeleteID.setOnClickListener(this);
		fm5_ClearID.setOnClickListener(this);
		
		fm5_fingerImage.setImageResource(R.drawable.zhiwen);
		
		for(int i=0; i<character.length;i++)
		{
			list.add(character[i]);
			
		}
		adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, list);
		fm5_IDTable.setAdapter(adapter);
		fm5_IDTable.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		
		
		
		mFingerprintPacket=new FingerprintPacket((UsbManager) getSystemService(Context.USB_SERVICE), this,
				ACTION_USB_PERMISSION);
		if(!mFingerprintPacket.mUSBOp.UsbFeatureSupported())
		{
			Dialog dialog = new AlertDialog.Builder(Finger_DEV.this)
					.setTitle("提示")
					.setMessage("您的手机不支持USB HOST，请更换其他手机再试！")
					.setPositiveButton("确认",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface arg0,
										int arg1) {
									System.exit(0);
								}
							}).create();
			dialog.setCanceledOnTouchOutside(false);
			dialog.show();
			
		}
		onCreateButtonSetup();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.finger__dev, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		int iRet;
		boolean bRet;
		int i,j;
		switch (v.getId()) 
		{
		case R.id.fmfinger_Opendev:
			bRet=mFingerprintPacket.OpenDeviceUsb();
			if(!bRet)
			{
				fm5_info.setTextColor(Color.parseColor("#FF0000"));//显示红色
				fm5_info.setText("Open the device failed ");	
				break;
			}
			else
			{
				fm5_info.setTextColor(Color.parseColor("#00FF00"));//显示绿色
				fm5_info.setText("Open the device successfully ");	
			}
			RefreshIDList();
			
			for(i=0;i<255;i++)
			{
				for(j=0;j<adapter.getCount();j++)
				{
					if(i==Integer.parseInt(adapter.getItem(j)))
						break;
				}
				if(j==adapter.getCount())
					break;
			}
			if(i>=100)
				i=0;
			fm5_fingerIDinput.setText(String.valueOf(i));
			onOpenButtonSetup();
			
			break;
		case R.id.fmfinger_Closedev:
			mFingerprintPacket.CloseDeviceUsb();
			fm5_info.setTextColor(Color.parseColor("#00FF00"));//显示绿色
			fm5_info.setText("Close the device successfully ");
			onCreateButtonSetup();
			break;
		case R.id.fmfinger_RefreshTable:
			RefreshIDList(); //
			fm5_info.setTextColor(Color.parseColor("#00FF00"));//显示绿色
			fm5_info.setText("Refresh user list successfully");
			break;
		case R.id.fmfinger_DeleteID:
			int nindex,npageID;
			nindex=fm5_IDTable.getCheckedItemPosition();
			//nindex=(int)fm5_IDTable.getSelectedItemId();

			String nStr=adapter.getItem(nindex);
			npageID=Integer.parseInt(nStr);
			iRet=mFingerprintPacket.USB_PS_DeletChar(npageID,1);
			if(iRet<0)
			{
				//删除失败
				fm5_info.setTextColor(Color.parseColor("#FF0000"));//显示红色
				fm5_info.setText("Delete fingerprint failed");
			}
			else
			{
				fm5_info.setTextColor(Color.parseColor("#00FF00"));//显示绿色
				fm5_info.setText("Delete fingerprint successfully");
				adapter.remove(nStr);
				adapter.notifyDataSetChanged();
				
			}
			break;
			
		
			
		case R.id.fmfinger_Enroll:
			myLoopStateFlag=true;
			//判断ID是否已经存在
			int tmpId;
			//int i;
			goonflag=true;
			tmpId=Integer.parseInt(fm5_fingerIDinput.getText().toString());
			for(i=0;i<adapter.getCount();i++)
			{
				if(tmpId==Integer.parseInt(adapter.getItem(i)))
					break;
				
			}
			if(i!=adapter.getCount())
			{
				EnrollIDIndex=tmpId;
				goonflag=false;
				AlertDialog alertDialog2 = new AlertDialog.Builder(this)
				        .setTitle("User ID already exists")
				        .setMessage("Whether to cover")
				        .setPositiveButton("yes", new DialogInterface.OnClickListener() {//添加"Yes"按钮
				            @Override
				            public void onClick(DialogInterface dialogInterface, int i) {
				            	goonflag=true;
				            	//这样就不会阻塞了
				            	
				    			onRunButtonSetup();
				    			mTask = new myTask();
				                mTask.execute();
				                //Toast.makeText(Finger_DEV.this, "这是确定按钮", Toast.LENGTH_SHORT).show();
				            }
				        })
				 
				        .setNegativeButton("No", new DialogInterface.OnClickListener() {//添加取消
				            @Override
				            public void onClick(DialogInterface dialogInterface, int i) {
				            	goonflag=false;
				                //Toast.makeText(Finger_DEV.this, "这是取消按钮", Toast.LENGTH_SHORT).show();
				            }
				        })
				        .create();
				alertDialog2.show();
				
			}
			if(goonflag==false)
				break;
			EnrollIDIndex=tmpId;
			onRunButtonSetup();
			mTask = new myTask();
            mTask.execute();
			break;
		case R.id.fmfinger_CancelOp:
			myLoopStateFlag=false;
			break;
		case R.id.fmfinger_Verify:
			onRunButtonSetup();
			myLoopStateFlag=true;
			mTaskVerify = new myTaskVerify();
			mTaskVerify.execute();
            break;
		case R.id.fmfinger_ClearID:
			iRet=mFingerprintPacket.USB_PS_Empty();
			if(iRet==0)
			{
				fm5_info.setTextColor(Color.parseColor("#00FF00"));//显示绿色
				fm5_info.setText("Clear ID library successfully");
				///清空列表
				adapter.clear();
				adapter.notifyDataSetChanged();
			}
			else
			{
				fm5_info.setTextColor(Color.parseColor("#FF0000"));//显示绿色
				fm5_info.setText("Clear ID library failed");	
			}
			break;
		case R.id.fmfinger_Quit:
			Intent intent_main = new Intent();
			intent_main.setClass(Finger_DEV.this, RM2091Activity.class);
			startActivity(intent_main);
			//System.exit(0);
			finish();
			break;
		default:
				break;
		
			
		}
	}
	private void onCreateButtonSetup() 
	{
		fm5_Opendev.setEnabled(true);
		fm5_Closedev.setEnabled(false);
		fm5_Quit.setEnabled(true);
		fm5_Enroll.setEnabled(false);
		fm5_Verify.setEnabled(false);
		fm5_CancelOp.setEnabled(false);
		fm5_RefreshTable.setEnabled(false);
		fm5_DeleteID.setEnabled(false);
		fm5_ClearID.setEnabled(false);
		
	}
	private void onOpenButtonSetup() 
	{
		fm5_Opendev.setEnabled(false);
		fm5_Closedev.setEnabled(true);
		fm5_Quit.setEnabled(true);
		fm5_Enroll.setEnabled(true);
		fm5_Verify.setEnabled(true);
		fm5_CancelOp.setEnabled(true);
		fm5_RefreshTable.setEnabled(true);
		fm5_DeleteID.setEnabled(true);
		fm5_ClearID.setEnabled(true);
		
	}
	private void onRunButtonSetup() 
	{
		fm5_Opendev.setEnabled(false);
		fm5_Closedev.setEnabled(false);
		fm5_Quit.setEnabled(false);
		fm5_Enroll.setEnabled(false);
		fm5_Verify.setEnabled(false);
		fm5_CancelOp.setEnabled(true);
		fm5_RefreshTable.setEnabled(false);
		fm5_DeleteID.setEnabled(false);
		fm5_ClearID.setEnabled(false);
		
	}
}
