package com.example.demoactivity;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

public class NameActivity extends Activity
{
	private Button name_button;
	private Spinner spinner;
	private ProgressDialog dialog;
	private Button yanqian_button1;
	private EditText editText3;
	private EditText QeditText2;
	private EditText passEdit;
	Handler handler;
	int i;
	long Sign;
	byte[] cert1;
	long[] certLen1;
	String nameOutData;
	long SignStatic;
	int flag;
	private static final String[] type={"MD5","SHA1","SHA224","SHA256","SHA384","SHA512"}; 
	 @Override
	    public void onCreate(Bundle savedInstanceState) {
		 requestWindowFeature(Window.FEATURE_NO_TITLE);
		 getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);


	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.name_main);
	       
	        Bundle b=getIntent().getExtras();
	         cert1=b.getByteArray("cert");
	         certLen1=b.getLongArray("certLen");
	        
	        spinner=(Spinner)findViewById(R.id.namespinner1);
	        ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,type);
	        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	        i=spinner.getSelectedItemPosition();
	        spinner.setAdapter(adapter);
	        spinner.setSelection(1, true);
	        
	        name_button=(Button)findViewById(R.id.namebutton1);
	        name_button.setOnClickListener(listener);
	        
	        yanqian_button1=(Button)findViewById(R.id.yanqian_button1);
	        yanqian_button1.setOnClickListener(listener);
	        
	        passEdit=(EditText)findViewById(R.id.password_editText1);
	        editText3=(EditText)findViewById(R.id.editText3);
	        editText3.setText("<?xml version=\"1.0\" encoding=\"utf-8\"?><root><Payments>147.54</Payments><PayeeName>eSecuTech</PayeeName><PayeeAccount>6210034472987234137</PayeeAccount></root>");
	        
	        QeditText2=(EditText)findViewById(R.id.QeditText2);
	        
	        handler=new Handler()
			{
				public void handleMessage(Message msg)
				{ 
					if(msg.arg1==0)
					{
						if(msg.what==0)
						{
						QeditText2.setText(nameOutData);
						}else if(msg.what==7){
							QeditText2.setText("");
						}else {
							
								QeditText2.setText(R.string.Signature_failed);
							}
					}
						else if(msg.arg1==1)
						{
							if(msg.what==0)
							{
								AlertDialog.Builder builder1=new AlertDialog.Builder(NameActivity.this);
								builder1.setMessage(R.string.Attestation_success);
								builder1.setIcon(R.drawable.ok);
								builder1.setTitle(R.string.title1);
								builder1.setPositiveButton(R.string.determine, new DialogInterface.OnClickListener() {
									
									public void onClick(DialogInterface dialog, int which) {
										// TODO Auto-generated method stub
										//dialog.dismiss();  
										dialog.dismiss();
										
									}
								});
				        		
								AlertDialog dialog=builder1.create();
								dialog.show();
				        	}
							else {
								AlertDialog.Builder builder1=new AlertDialog.Builder(NameActivity.this);
								builder1.setMessage(R.string.Attestation_Failure);
								builder1.setIcon(R.drawable.warning);
								builder1.setTitle(R.string.title);
								builder1.setPositiveButton(R.string.determine, new DialogInterface.OnClickListener() {
									
									public void onClick(DialogInterface dialog, int which) {
										// TODO Auto-generated method stub
										//dialog.dismiss();  
										dialog.dismiss();
										
									}
								});
				        		
								AlertDialog dialog=builder1.create();
								dialog.show();
				        	}
							
						}
					
					
				}
				
			};
	        
	        
	 }
	 private OnClickListener listener=new OnClickListener()
	 {

		public void onClick(View v) {
			
			if(v.getId()==R.id.namebutton1)
			{	String signdata=QeditText2.getText().toString();
				if(!("".equals(signdata))){
					Long clear = 7l;
					flag=0;
        			sendMsg(clear,flag);
				}
				dialog = new ProgressDialog(NameActivity.this);
				dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
				dialog.setTitle(R.string.tip);
	            dialog.setMessage(v.getContext().getString(R.string.Are_signature));
	            dialog.setIndeterminate(false);
	            dialog.setCancelable(true);
	            dialog.show();
	           
	            new Thread()
	            {
	            	public void run()
	            	{
	            		try {
	            			String pass=passEdit.getText().toString();
	            			byte[] userPin = pass.getBytes();
	            			long userPinLen=pass.length();
	            			
	            			byte[] cert=cert1;
	            			long certLength=certLen1[0];
	            			
	            			String data=editText3.getText().toString();
	            			byte[] InData=data.getBytes("UTF-8");
	            			long InDataLength=InData.length;
	            			long HashOID=spinner.getSelectedItemId();
	            			byte[] OutData=new byte[512];
	            			long[] OutDataLen=new long[1];
	            			int outLen = 0;
	            			
	            			Sign=sign(userPin, userPinLen, InData, InDataLength, cert, certLength, HashOID, OutData, OutDataLen);

	            			outLen = (int)OutDataLen[0];
	            			nameOutData=new String(OutData, 0, outLen);
	            			flag=0;
	            			sendMsg(Sign,flag);
	            			dialog.dismiss();

						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} 
	            		
	            	}
	            }.start();
			}
			if(v.getId()==R.id.yanqian_button1)
			{
	            new Thread()
	            {
	            	public void run()
	            	{
	            		try {
	            			long HashOID=spinner.getSelectedItemId();
	            			String data=editText3.getText().toString();
	            			byte[] InData=data.getBytes("UTF-8");
	            			long InDataLength=InData.length;
	            			byte[] cert=cert1;
	            			long certLength=certLen1[0];
	            			String signed=QeditText2.getText().toString();
	            			byte[] signedData=hexStringToBytes(signed);
	            			long signedDataLen=signedData.length;
	            			SignStatic=verifySignStatic(HashOID, 
 									InData, InDataLength,
 									cert, certLength,
 									signedData,signedDataLen);
	            			flag=1;
	            			sendMsg(SignStatic,flag);
							//dialog.dismiss();
							
							
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} 
	            	}
	            }.start();
			}
			
		}
		 
	 };
	 public byte[] hexStringToBytes(String s) {
			if (s == null)
				return null;
			int sz = s.length();
			byte result[] = new byte[sz / 2];
			for (int i = 0; i < sz; i += 2)
			{
				result[i / 2] = (byte) (hexCharToInt(s.charAt(i)) << 4 | hexCharToInt(s
						.charAt(i + 1)));
			}
			return result;
		}
	 int hexCharToInt(char c) {
			if (c >= '0' && c <= '9')
				return c - 48;
			if (c >= 'A' && c <= 'F')
				return (c - 65) + 10;
			if (c >= 'a' && c <= 'f')
				return (c - 97) + 10;
			else
				throw new RuntimeException((new StringBuilder()).append(
						"invalid hex char '").append(c).append("'").toString());
		}

	 
	


	private void sendMsg(long result,int i)
		{
			Message msg=new Message();
			msg.what=(int)result;
			msg.arg1=i;
			handler.sendMessage(msg);
		}
	 
	 public static native long sign(byte[] userPin, long userPinLen,
			 						byte[] InData, long InDataLength,
			 						byte[] cert, long certLength, 
			 						long HashOID, 
			 						byte[] OutData, long[] OutDataLen);
	 
	 public static native long verifySignStatic(long HashOID, 
			 									byte[] InData, long InDataLength,
			 									byte[] cert, long certLength,
			 									byte[] signedData, long signedDataLen);
	 
	 static {
	        int version = 0;   
	        try {   
	           version = Integer.valueOf(android.os.Build.VERSION.SDK);   
	        } catch (NumberFormatException e) {   
	        }
	        if(version < 9)
	           System.loadLibrary("Demo8");
	        else
	           System.loadLibrary("Demo"); 
	       }
	
}
