package com.example.possdkforandroid;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import POSAPI.POSBluetoothAPI;
import POSAPI.POSInterfaceAPI;
import POSSDK.POSSDK;
import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.ToggleButton;

public class BlueActivity extends Activity {
	
	//SDK variable
	private POSBluetoothAPI mBluetoothManager; 
	public static POSSDK pos_blue = null;
	private POSInterfaceAPI interface_blue = null;
	private TestPrintInfo testprint;
	private String cur_address = null;

	//Returned Value Statement
	public static final int POS_SUCCESS=1000;		//success	
	public static final int ERR_PROCESSING = 1001;	//processing error
	public static final int ERR_PARAM = 1002;		//parameter error
	private int error_code=0;
		
	
	// Print Mode
	private static final int PRINT_MODE_STANDARD = 0;
	private static final int PRINT_MODE_PAGE = 1;
	public static int printMode = PRINT_MODE_STANDARD;

	//Button variable
	private ToggleButton btSwitchBtn; // Bluetooth on-off
	private Button setCanBeDiscoverBtn; // Set visible 
	private Button getPairedDevsBtn; // Display the paired Bluetooth devices 
	private Button searchDevBtn; // Search Bluetooth devices 
	private Button disconnectBtn;// DisConnect devices

	private RadioGroup radiogroup; 
	private RadioButton standardmodeRB; // Stand Mode
	private RadioButton pagemodeRB; // Page Mode

	private Button printBitmapBtn; // Test Print Bitmap
	private Button printTextBtn; // Test Print Text
	private Button printBarcodeBtn; // Test Print BarCode
	private Button printPDF417Btn; // Test Print PDF417
	private Button printQRBtn; // Test Print QR
	private Button printGS1Btn; //Test Print GS1
	private Button queryStateBtn; // Get Printer State
	private Button printFeedLineBtn; //Test Print FeedPaper
	private Button printCutPaperBtn; //Test Print CutPaper
	private Button printRasterBitmapBtn; //Test Print RasterCharacter
	private Button printUserDefCharBtn;	//Test Print User-defined character

	private RadioButton r1;
	private RadioButton r2;
	private RadioButton r3;
	private RadioButton r4;
	private RadioButton r5;
	private RadioButton r6;
	private RadioButton r7;
	private RadioButton r8;

	byte btemps[] = new byte[8];
	
	// A list of Bluetooth devices 
	ListView lvBTDevices;
	ArrayAdapter<String> adtDevices;
	List<String> lstDevices = new ArrayList<String>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.blue_demo);
        
		r1 = (RadioButton) findViewById(R.id.blue_r1);
		r2 = (RadioButton) findViewById(R.id.blue_r2);
		r3 = (RadioButton) findViewById(R.id.blue_r3);
		r4 = (RadioButton) findViewById(R.id.blue_r4);
		r5 = (RadioButton) findViewById(R.id.blue_r5);
		r6 = (RadioButton) findViewById(R.id.blue_r6);
		r7 = (RadioButton) findViewById(R.id.blue_r7);
		r8 = (RadioButton) findViewById(R.id.blue_r8);
		
		//TestPrint variable
		testprint = new TestPrintInfo();

		// Radio listeners registered a device was found.
		IntentFilter intentfilter = new IntentFilter();
		intentfilter.addAction(BluetoothDevice.ACTION_FOUND);
		intentfilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
		this.registerReceiver(mReceiver, intentfilter);

		mBluetoothManager = POSBluetoothAPI.getInstance(BlueActivity.this);
		interface_blue = POSBluetoothAPI.getInstance(BlueActivity.this);
//		pos_blue = new POSSDK(mBluetoothManager);
		if (!mBluetoothManager.isBTSupport()) {
			Toast.makeText(BlueActivity.this, "This machine is not support for bluetooth.", Toast.LENGTH_LONG).show();
		}

		// A list of Bluetooth devices
		lvBTDevices = (ListView) findViewById(R.id.blue_lvDevices);
		lvBTDevices = (ListView) this.findViewById(R.id.blue_lvDevices);
		adtDevices = new ArrayAdapter<String>(BlueActivity.this,
				android.R.layout.simple_list_item_1, lstDevices);
		lvBTDevices.setAdapter(adtDevices);
		lvBTDevices.setOnItemClickListener(new ItemClickEvent());
		
		//************************************************************************************************
		// Bluetooth on-off
		btSwitchBtn = (ToggleButton) findViewById(R.id.blue_bluetooth_switch_btn);
		// set state of ToggleButton
		error_code = mBluetoothManager.getState();
		if (error_code == POSBluetoothAPI.STATE_OFF)
			btSwitchBtn.setChecked(false);
		if (mBluetoothManager.getState() == POSBluetoothAPI.STATE_ON)
			btSwitchBtn.setChecked(true);
		btSwitchBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (btSwitchBtn.isChecked() == true) {
					if (!mBluetoothManager.openBluetooth()) {
						Toast.makeText(BlueActivity.this, "This machine is not support for bluetooth.", Toast.LENGTH_LONG)
								.show();
						btSwitchBtn.setChecked(false);
					}
				}

				if (btSwitchBtn.isChecked() == false) {
					if (mBluetoothManager.closeBluetooth()) {
						lstDevices.clear();
						adtDevices.notifyDataSetChanged(); // Refresh the list

					} else {
						Toast.makeText(BlueActivity.this, "Failed to close bluetooth.", Toast.LENGTH_LONG)
								.show();
					}
				}

			}
		});
		
		//************************************************************************************************
		// Set local bluetooth visible
		setCanBeDiscoverBtn = (Button) findViewById(R.id.blue_set_canbediscover_btn);
		setCanBeDiscoverBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (mBluetoothManager.getState() == POSBluetoothAPI.STATE_OFF) {
					Toast.makeText(BlueActivity.this, "Bluetooth not open! Please open the bluetooth.", Toast.LENGTH_LONG)
							.show();
				} else {
					mBluetoothManager.setDiscoverable(200);
				}

			}
		});
		
		//***********************************************************************************************
		// Get bluetooth devices of paired 
		getPairedDevsBtn = (Button) findViewById(R.id.blue_get_paired_devs_btn);
		getPairedDevsBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mBluetoothManager.cancelDiscovery();

				if (mBluetoothManager.getState() == POSBluetoothAPI.STATE_OFF) {
					Toast.makeText(BlueActivity.this, "Bluetooth not open! Please open the bluetooth.", Toast.LENGTH_LONG)
							.show();
				} else {
					lstDevices.clear(); // Empty list
					adtDevices.notifyDataSetChanged(); // Refresh the list

					Set<BluetoothDevice> bdv = mBluetoothManager
							.getBondedDevices();
					if (bdv.size() > 0) {
						// Iterative search to bluetooth information 
						for (Iterator<BluetoothDevice> iterator = bdv
								.iterator(); iterator.hasNext();) {
							BluetoothDevice bluetoothDevice = (BluetoothDevice) iterator
									.next();

							String str = bluetoothDevice.getName() + "|"
									+ bluetoothDevice.getAddress();
//							lstDevices.clear();
							// To prevent duplication of add 
							if (lstDevices.indexOf(str) == -1) {
								lstDevices.add(str); // Get device name and MAC Address
							}
							adtDevices.notifyDataSetChanged();// Refresh the list
						}
					}
				}

			}
		});
		
		//*************************************************************************************************
		// Query bluetooth devices 
		searchDevBtn = (Button) findViewById(R.id.blue_search_dev_btn);
		searchDevBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (mBluetoothManager.getState() == POSBluetoothAPI.STATE_OFF) {
					Toast.makeText(BlueActivity.this, "Bluetooth not open! Please open the bluetooth.", Toast.LENGTH_LONG)
							.show();
				} else {
					lstDevices.clear(); 
					adtDevices.notifyDataSetChanged();
					mBluetoothManager.startDiscovery();
				}
			}
		});
		
		//*************************************************************************************************
		// DisConnect devices
		disconnectBtn = (Button)findViewById(R.id.blue_disconnect_btn);
		disconnectBtn.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(pos_blue != null){
					pos_blue=null;
					interface_blue.CloseDevice();
					cur_address=null;	
					Toast.makeText(BlueActivity.this, "The connection to the printer has shut down.", Toast.LENGTH_LONG)
					.show();
				}

			}
			
		});
		
		//*************************************************************************************************
		// Choose PrintMode
		radiogroup = (RadioGroup) findViewById(R.id.blue_radiogroup);
		standardmodeRB = (RadioButton) findViewById(R.id.blue_radiobutton_standard);
		pagemodeRB = (RadioButton) findViewById(R.id.blue_radiobutton_page);
		radiogroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(RadioGroup group, int checkedId) {
						// TODO Auto-generated method stub
						if (mBluetoothManager.getConnectState() == POSBluetoothAPI.STATE_CONNECTED)
						{
							if (checkedId == standardmodeRB.getId()) {
								printMode = PRINT_MODE_STANDARD;
								error_code = pos_blue.systemSelectPrintMode(PRINT_MODE_STANDARD);
							} else if (checkedId == pagemodeRB.getId()) {
								printMode = PRINT_MODE_PAGE;
								error_code = pos_blue.systemSelectPrintMode(PRINT_MODE_PAGE);
							}		
						}
						else
						{
							cur_address=null;
							Toast.makeText(BlueActivity.this, "Not connected devices.", Toast.LENGTH_LONG).show();	
						}

					}
				});
		
		//**************************************************************************************************
		// PrintBitmap
		printBitmapBtn = (Button) findViewById(R.id.blue_print_bitmap);
		printBitmapBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mBluetoothManager.getConnectState() == POSBluetoothAPI.STATE_CONNECTED) 
				{
    			    Intent intent = new Intent();
    				intent.setClass(BlueActivity.this, PrintBitmapActivity.class);
    				startActivity(intent);	
				} 
				else 
				{
					cur_address=null;
					Toast.makeText(BlueActivity.this, "Not connected devices.", Toast.LENGTH_LONG).show();
				}
			}
		});

		//**************************************************************************************************
		// PrintText
		printTextBtn = (Button) findViewById(R.id.blue_print_text);
		printTextBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mBluetoothManager.getConnectState() == POSBluetoothAPI.STATE_CONNECTED) {
    			    Intent intent = new Intent();
    				intent.setClass(BlueActivity.this, PrintTextActivity.class);
    				startActivity(intent);    
				} 
				else 
				{
					cur_address=null;
					Toast.makeText(BlueActivity.this, "Not connected devices.", Toast.LENGTH_LONG).show();
				}
			}
		});

		//**************************************************************************************************
		// PirntBarCode
		printBarcodeBtn = (Button) findViewById(R.id.blue_print_barcode);
		printBarcodeBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mBluetoothManager.getConnectState() == POSBluetoothAPI.STATE_CONNECTED) 
				{
    			    Intent intent = new Intent();
    				intent.setClass(BlueActivity.this, BarCodeActivity.class);
    				startActivity(intent);	
				} 
				else 
				{
					cur_address=null;
					Toast.makeText(BlueActivity.this, "Not connected devices.", Toast.LENGTH_LONG).show();
				}
			}
		});
		
		//***************************************************************************************************
		// PrintPDF417
		printPDF417Btn = (Button) findViewById(R.id.blue_print_pdf417);
		printPDF417Btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (mBluetoothManager.getConnectState() == POSBluetoothAPI.STATE_CONNECTED) 
				{
    			    Intent intent = new Intent();
    				intent.setClass(BlueActivity.this, PDF417CodeActivity.class);
    				startActivity(intent);	
				} 
				else 
				{
					cur_address=null;
					Toast.makeText(BlueActivity.this, "Not connected devices.", Toast.LENGTH_LONG).show();
				}
			}
		});
		
		//************************************************************************************************
		// PrintQR
		printQRBtn = (Button) findViewById(R.id.blue_print_qr);
		printQRBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mBluetoothManager.getConnectState() == POSBluetoothAPI.STATE_CONNECTED) 
				{
    			    Intent intent = new Intent();
    				intent.setClass(BlueActivity.this, QRCodeActivity.class);
    				startActivity(intent);	
				} 
				else 
				{
					cur_address=null;
					Toast.makeText(BlueActivity.this, "Not connected devices.", Toast.LENGTH_LONG).show();
				}
			}
		});
		
		//**************************************************************************************************
		// PrintGS1
		printGS1Btn = (Button)findViewById(R.id.blue_print_gs1);
		printGS1Btn.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				if(mBluetoothManager.getConnectState() == POSBluetoothAPI.STATE_CONNECTED)
				{
				    Intent intent = new Intent();
					intent.setClass(BlueActivity.this, GS1CodeActivity.class);
					startActivity(intent);			
				}
				else
        		{
					cur_address=null;
					Toast.makeText(BlueActivity.this, "Not connected devices.", Toast.LENGTH_LONG).show();
        		}
				
			}
			
		});
		
		//**************************************************************************************************
		//Print RasterCharacter
		printRasterBitmapBtn = (Button)findViewById(R.id.blue_print_rasterimg);
		printRasterBitmapBtn.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				if(mBluetoothManager.getConnectState() == POSBluetoothAPI.STATE_CONNECTED)
				{
				    Intent intent = new Intent();
					intent.setClass(BlueActivity.this, RasterBitmapActivity.class);
					startActivity(intent);			
				}
				else
        		{
					cur_address=null;
					Toast.makeText(BlueActivity.this, "Not connected devices.", Toast.LENGTH_LONG).show();
        		}
			}
		});
		//*************************************************************************************************
		//Print User-defined character 
		printUserDefCharBtn = (Button)findViewById(R.id.blue_print_userfont);
		printUserDefCharBtn.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				if(mBluetoothManager.getConnectState() == POSBluetoothAPI.STATE_CONNECTED)
				{
					error_code = testprint.TestUserDefinedCharacter(pos_blue, printMode);
					if(error_code != POS_SUCCESS)
					{
						cur_address=null;
						Toast.makeText(BlueActivity.this, "Failed to Print UserDefinedCharacter.",Toast.LENGTH_LONG).show();	
					}
				}
				else
				{
					cur_address=null;
					Toast.makeText(BlueActivity.this, "Not connected devices.", Toast.LENGTH_LONG).show();
				}
				
			}
			
		});
		
		//**************************************************************************************************
		//FeedPaper
		printFeedLineBtn = (Button)findViewById(R.id.blue_print_feed);
		printFeedLineBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if(mBluetoothManager.getConnectState() == POSBluetoothAPI.STATE_CONNECTED)
				{
					error_code = testprint.TestFeedLine(pos_blue, printMode);
	        		if(error_code != POS_SUCCESS)
	        		{
	        			cur_address=null;
	        			Toast.makeText(BlueActivity.this, "Failed to Feed Paper.",Toast.LENGTH_LONG).show();
	        		}					
				}
				else
				{
					cur_address=null;
					Toast.makeText(BlueActivity.this, "Not connected devices.", Toast.LENGTH_LONG).show();
				}

			}
		});
		
		//*************************************************************************************************
		//CutPaper
		printCutPaperBtn = (Button)findViewById(R.id.blue_print_cut);
		printCutPaperBtn.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				if(mBluetoothManager.getConnectState() == POSBluetoothAPI.STATE_CONNECTED)
				{
					error_code = testprint.TestCutPaper(pos_blue, printMode);
					if(error_code != POS_SUCCESS)
					{
						cur_address=null;
						Toast.makeText(BlueActivity.this, "Failed to Cut Paper.",Toast.LENGTH_LONG).show();	
					}
				}
				else
				{
					cur_address=null;
					Toast.makeText(BlueActivity.this, "Not connected devices.", Toast.LENGTH_LONG).show();
				}
				
			}
			
		});
		//*************************************************************************************************
		// Get The Printer State
		queryStateBtn = (Button) findViewById(R.id.blue_query_state);
		queryStateBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				byte[] posStateTemp = new byte[1];
				int result;
					if(pos_blue != null){
						result = testprint.POSNETQueryStatus(pos_blue,posStateTemp);
						if(result != POS_SUCCESS) 
						{
							result = testprint.POSNETQueryStatus(pos_blue,posStateTemp);
							if(result != POS_SUCCESS)
							{
								result = testprint.POSNETQueryStatus(pos_blue,posStateTemp);	
							}
						}
						if (result == POS_SUCCESS) {
							byte btemp[] = new byte[8];
							byte bitindex = 1;
							for (int i = 0; i < btemp.length; i++) {
								btemp[i] = (byte) (posStateTemp[0] & bitindex);
								bitindex = (byte) (bitindex << 1);

							}
							if (btemp[0] == 0) {	//CashDrawer Open
								r1.setChecked(false);	
							} else {
								r1.setChecked(true);
							}
							if (btemp[1] == 0) {	//Offline
								r2.setChecked(false);
							} else {
								r2.setChecked(true);
							}
							if (btemp[2] == 0) {	//Cover Open
								r3.setChecked(false);
							} else {
								r3.setChecked(true);
							}
							if (btemp[3] == 0) {	//Feeding
								r4.setChecked(false);
							} else {
								r4.setChecked(true);
							}
							if (btemp[4] == 0) {	//Printer Error
								r5.setChecked(false);
							} else {
								r5.setChecked(true);
							}
							if (btemp[5] == 0) {	//Cutter Error
								r6.setChecked(false);
							} else {
								r6.setChecked(true);
							}
							if (btemp[6] == 0) {	//Paper	Near End
								r7.setChecked(false);
							} else {
								r7.setChecked(true);
							}
							if (btemp[7] == 0) {	//Paper End
								r8.setChecked(false);
							} else {
								r8.setChecked(true);
							}
							btemp = null;
						} else {
							Toast.makeText(BlueActivity.this, "Failed to read data.",
									Toast.LENGTH_LONG).show();
						}
					}else{
						cur_address=null;
						Toast.makeText(BlueActivity.this, "Not connected devices.", Toast.LENGTH_LONG).show();
					}

			}
		});
    }
    
	// The list click listener
	class ItemClickEvent implements AdapterView.OnItemClickListener {

		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {

			// Stop Search
			if (mBluetoothManager.isDiscovery()) {
				mBluetoothManager.cancelDiscovery();
			}

			// Split String,Get MAC Address
			String str = lstDevices.get(arg2);
			String[] values = str.split("\\|");
			String address = values[1];

			setTitle("Mac::" + address);
			
			// connect devices
			if(address.equals(cur_address)){
				Toast.makeText(BlueActivity.this, "Connection has been established £¬you can send the data.", Toast.LENGTH_LONG)
				.show();	
			}else{
				Toast.makeText(BlueActivity.this, "Connection is establishing  £¬Please wait.",
						Toast.LENGTH_LONG).show();
				if (interface_blue.OpenDevice(address) == POS_SUCCESS) {
					cur_address = address;
					pos_blue = new POSSDK(interface_blue);
					Toast.makeText(BlueActivity.this, "Connection has been established £¬you can send the data.", Toast.LENGTH_LONG)
							.show();
				}else{
					interface_blue.CloseDevice();
					cur_address=null;
					Toast.makeText(BlueActivity.this, "Failed to connect device, please try again.", Toast.LENGTH_LONG).show();
				}	
			}
		}
	}
	
	// Radio listening object£¬search for bluetooth devices 
	private final BroadcastReceiver mReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();

			if (BluetoothDevice.ACTION_FOUND.equals(action)) { // search devices
				BluetoothDevice device = intent
						.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				System.out.println(device.getName() + "------"
						+ device.getAddress());

				String str = device.getName() + "|" + device.getAddress();
				if (lstDevices.indexOf(str) == -1) 
					lstDevices.add(str); // Get devices name and MAC address

				adtDevices.notifyDataSetChanged(); //Refresh the list 
			} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
					.equals(action)) { // search end

			}
		}
	};
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}
}
