package com.example.possdkforandroid;

import java.util.ArrayList;
import java.util.List;

import POSAPI.POSInterfaceAPI;
import POSAPI.POSWIFIAPI;
import POSSDK.POSSDK;
import android.os.Bundle;
import android.provider.Settings;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
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.TextView;
import android.widget.Toast;
import android_wifi_api.SearchPortInfo;
import android_wifi_api.WiFiSDKAPI;

public class WIFIActivity extends Activity {
	//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
	

	
	//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;
	
	
	//SDK variable
	private WiFiSDKAPI mWifiAdmin;
	public static POSSDK pos_wifi = null;	
	private POSSDK pos_state = null;
	private POSInterfaceAPI interface_wifi = null;
	private POSInterfaceAPI	interface_state = null;
//	private POSWIFIAPI interface_wifi = null;
	private TestPrintInfo testprint;
	private int error_code = 0;
	
	//WIFI port variable
	private static final int POSPORT = 9100; 	// The port handle of Processing instruction 
	private static final int STATEPORT = 4000; 	// The port handle of Query State
	private static String POSIP = null; 
//	private static final String SSID = "ciscosb-1";
	
	private static final int SearchPortMAX = 10;
	private SearchPortInfo port_info[] = new SearchPortInfo[SearchPortMAX];
	private int sch_prt_num = 0;
	private String address;
	
	//Button variable
	private Button addNetWork; // Jump to the WIFI setup
	private Button setLocalIP; // set IP
	private Button connectWIFI; // connect WIFI
	private Button disConnectWIFI; // disconnect WIFI

	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];
	private long lastWriteTime = System.currentTimeMillis();
	
	// A list of WIFI devices 
	ListView lvBTDevices;
	ArrayAdapter<String> adtDevices;
	List<String> lstDevices = new ArrayList<String>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.wifi_demo);
            
        //Get State RadioButton Object
		r1 = (RadioButton) findViewById(R.id.wifi_r1);
		r2 = (RadioButton) findViewById(R.id.wifi_r2);
		r3 = (RadioButton) findViewById(R.id.wifi_r3);
		r4 = (RadioButton) findViewById(R.id.wifi_r4);
		r5 = (RadioButton) findViewById(R.id.wifi_r5);
		r6 = (RadioButton) findViewById(R.id.wifi_r6);
		r7 = (RadioButton) findViewById(R.id.wifi_r7);
		r8 = (RadioButton) findViewById(R.id.wifi_r8);
		
		//TestPrint variable
		testprint = new TestPrintInfo();
		
		
//		class CheckWriteSocketConnectionState extends Thread {
//
//			public void run() {
//				while (interface_wifi != null) {
//					try {
//						long currentTimeMillis = System.currentTimeMillis();
//						if (currentTimeMillis - lastWriteTime > 60000){
//							interface_wifi.CloseDevice();
//							interface_wifi.OpenDevice(POSIP, POSPORT);
//							updateLastWriteTime();
//						}
//					} catch (Exception e) {
//						Toast.makeText(WIFIActivity.this,
//								"The connection to the printer has shut down, please click 'Connect Wi-Fi' button, try to connect to the printer.",
//								Toast.LENGTH_LONG).show();
//					}
//				}
//			}
//		}
		
		// A list of WIFI devices
		lvBTDevices = (ListView) findViewById(R.id.wifi_lvDevices);
		lvBTDevices = (ListView) this.findViewById(R.id.wifi_lvDevices);
		adtDevices = new ArrayAdapter<String>(WIFIActivity.this,
				android.R.layout.simple_list_item_1, lstDevices);
		lvBTDevices.setAdapter(adtDevices);
		lvBTDevices.setOnItemClickListener(new ItemClickEvent());
		
		//**************************************************************************************************
		//Connect WIFI
		
		mWifiAdmin = WiFiSDKAPI.getInstance(WIFIActivity.this);
		connectWIFI = (Button) findViewById(R.id.wifi_connect_network);
		connectWIFI.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(POSIP == null){
					Toast.makeText(WIFIActivity.this, "please click 'Search Device' button, try to search to the printer", Toast.LENGTH_LONG).show();
				}else{
				if (mWifiAdmin.isWifiEnabled()) {
					//Get Printer IP
					
					// Open device
					interface_wifi = new POSWIFIAPI();
					error_code = interface_wifi.OpenDevice(POSIP, POSPORT);
					if(error_code != POS_SUCCESS){
						Toast.makeText(WIFIActivity.this, "Failed to connect device, please try again.", Toast.LENGTH_LONG).show();
					}else{
						pos_wifi = new POSSDK(interface_wifi);
						interface_state = new POSWIFIAPI();
						error_code = interface_state.OpenDevice(POSIP, STATEPORT);
						if (error_code == POS_SUCCESS) {
							pos_state = new POSSDK(interface_state);					
							Toast.makeText(WIFIActivity.this, "Connection has been established £¬you can send the data.", Toast.LENGTH_LONG)
									.show();
						}else{
							Toast.makeText(WIFIActivity.this, "Failed to connect device, please try again.", Toast.LENGTH_LONG).show();
						}
					}
					new CheckWriteSocketConnectionState().start();

				} else {
					Toast.makeText(WIFIActivity.this, "WIFI Not Available", Toast.LENGTH_LONG).show();
				}
			}
				
			}
		});
		
		//*************************************************************************************************
		// DisConnect WIFI
		disConnectWIFI = (Button) findViewById(R.id.wifi_disconnect_wifi);
		disConnectWIFI.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// if(mWifiAdmin.isWifiEnabled()){
				RefreshInfo();
				if (pos_wifi == null && pos_state == null) {
					Toast.makeText(WIFIActivity.this, "The connection to the printer has shut down.", Toast.LENGTH_LONG)
							.show();
				} else {
					if (pos_wifi != null) {
						interface_wifi.CloseDevice();
						interface_wifi = null;
						pos_wifi = null;
					}
					if (pos_state != null) {
						interface_state.CloseDevice();
						interface_state = null;
						pos_state = null;
					}
					Toast.makeText(WIFIActivity.this, "The connection to the printer has shut down.", Toast.LENGTH_LONG)
							.show();
				}
			}
		});
		
		//*************************************************************************************************
		// Set WIFI Parameter
		addNetWork = (Button) findViewById(R.id.wifi_add_wifi);
		addNetWork.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
			}
		});

		//************************************************************************************************
		// Search printer devices
		setLocalIP = (Button) findViewById(R.id.wifi_set_ip);
		setLocalIP.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				//Set Local IP
//				startActivity(new Intent(Settings.ACTION_WIFI_IP_SETTINGS));
				
				
				int i = 0;
				RefreshInfo();
				
				
				
				if(interface_wifi == null)
				{
					interface_wifi  = new POSWIFIAPI();	
					interface_state = new POSWIFIAPI();
				}
				for(i = 0; i < SearchPortMAX; i++){
					port_info[i] = new SearchPortInfo();
				}
				Toast.makeText(WIFIActivity.this, "Searching devices, ", Toast.LENGTH_LONG).show();
				sch_prt_num = interface_wifi.WIFISearchPort(port_info, SearchPortMAX);
				if(sch_prt_num <= 0){
					Toast.makeText(WIFIActivity.this, "Not search WIFI Printer devices ", Toast.LENGTH_LONG).show();
				}else{
					for(i = 0; i < sch_prt_num;i++){
						String str = port_info[i].GetPrtName() + "|" + port_info[i].GetIPAddress();
						if (lstDevices.indexOf(str) == -1) 
							lstDevices.add(str); // Get devices name and IP address

						adtDevices.notifyDataSetChanged(); //Refresh the list 
						
					}
				}
			}
			
		});
		
		//************************************************************************************************
		// Choose PrintMode
		radiogroup = (RadioGroup) findViewById(R.id.wifi_radiogroup);
		standardmodeRB = (RadioButton) findViewById(R.id.wifi_radiobutton_standard);
		pagemodeRB = (RadioButton) findViewById(R.id.wifi_radiobutton_page);
		radiogroup
				.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(RadioGroup group, int checkedId) {
						// TODO Auto-generated method stub
						if(pos_wifi != null){
							if (checkedId == standardmodeRB.getId()) {
								printMode = PRINT_MODE_STANDARD;
								error_code = pos_wifi.systemSelectPrintMode(PRINT_MODE_STANDARD);
							} else if (checkedId == pagemodeRB.getId()) {
								printMode = PRINT_MODE_PAGE;
								error_code = pos_wifi.systemSelectPrintMode(PRINT_MODE_PAGE);
							}
						}
						else{
							Toast.makeText(WIFIActivity.this,
									"The connection to the printer has shut down, please click 'Connect Wi-Fi' button, try to connect to the printer.", Toast.LENGTH_LONG).show();
						}

					}
			});
        
		//************************************************************************************************
        //PrintBitmap
        printBitmapBtn = (Button)findViewById(R.id.wifi_print_bitmap);
        printBitmapBtn.setOnClickListener(new OnClickListener(){
        	
        	public void onClick(View v){
        		if(pos_wifi != null)
        		{
    			    Intent intent = new Intent();
    				intent.setClass(WIFIActivity.this, PrintBitmapActivity.class);
    				startActivity(intent);	
        		}
        		else 
        		{
					Toast.makeText(WIFIActivity.this,
							"The connection to the printer has shut down, please click 'Connect Wi-Fi' button, try to connect to the printer.", Toast.LENGTH_LONG).show();
				}

        	}
        });
        
        //*****************************************************************************************************
        //PrintText
        printTextBtn = (Button)findViewById(R.id.wifi_print_text);
        printTextBtn.setOnClickListener(new OnClickListener(){
        	
        	public void onClick(View v){
        		if(pos_wifi != null)
        		{
    			    Intent intent = new Intent();
    				intent.setClass(WIFIActivity.this, PrintTextActivity.class);
    				startActivity(intent);   
        		}
        		else 
        		{
					Toast.makeText(WIFIActivity.this,
							"The connection to the printer has shut down, please click 'Connect Wi-Fi' button, try to connect to the printer.", Toast.LENGTH_LONG).show();
				}
        	}
        });
        
        //******************************************************************************************************
		// PirntBarCode
		printBarcodeBtn = (Button) findViewById(R.id.wifi_print_barcode);
		printBarcodeBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if(pos_wifi != null)
				{
				    Intent intent = new Intent();
					intent.setClass(WIFIActivity.this, BarCodeActivity.class);
					startActivity(intent);		
				}
				else 
				{
					Toast.makeText(WIFIActivity.this,
							"The connection to the printer has shut down, please click 'Connect Wi-Fi' button, try to connect to the printer.", Toast.LENGTH_LONG).show();
				}
			}
		});
        
		//***************************************************************************************************
		// PrintPDF417
		printPDF417Btn = (Button) findViewById(R.id.wifi_print_pdf417);
		printPDF417Btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if(pos_wifi != null)
				{
				    Intent intent = new Intent();
					intent.setClass(WIFIActivity.this, PDF417CodeActivity.class);
					startActivity(intent);	
	    
				}
	    		else 
        		{
					Toast.makeText(WIFIActivity.this,
							"The connection to the printer has shut down, please click 'Connect Wi-Fi' button, try to connect to the printer.", Toast.LENGTH_LONG).show();
				}	

			}
		});
		
		//****************************************************************************************************
		// PrintQR
		printQRBtn = (Button) findViewById(R.id.wifi_print_qr);
		printQRBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if(pos_wifi != null)
				{
				    Intent intent = new Intent();
					intent.setClass(WIFIActivity.this, QRCodeActivity.class);
					startActivity(intent);	

				}
        		else 
        		{
					Toast.makeText(WIFIActivity.this,
							"The connection to the printer has shut down, please click 'Connect Wi-Fi' button, try to connect to the printer.", Toast.LENGTH_LONG).show();
				}	
			}
		});
		
		//**************************************************************************************************
		//PrintGS1
		printGS1Btn = (Button)findViewById(R.id.wifi_print_gs1);
		printGS1Btn.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				if(pos_wifi != null)
				{
				    Intent intent = new Intent();
					intent.setClass(WIFIActivity.this, GS1CodeActivity.class);
					startActivity(intent);			
				}
				else
        		{
					Toast.makeText(WIFIActivity.this,
							"The connection to the printer has shut down, please click 'Connect Wi-Fi' button, try to connect to the printer.", Toast.LENGTH_LONG).show();
        		}
				
			}
			
		});
		
		//**************************************************************************************************
		//Print RasterCharacter
		printRasterBitmapBtn = (Button)findViewById(R.id.wifi_print_rasterimg);
		printRasterBitmapBtn.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				if(pos_wifi != null)
				{
				    Intent intent = new Intent();
					intent.setClass(WIFIActivity.this, RasterBitmapActivity.class);
					startActivity(intent);			
				}
				else
        		{
					Toast.makeText(WIFIActivity.this,
							"The connection to the printer has shut down, please click 'Connect Wi-Fi' button, try to connect to the printer.", Toast.LENGTH_LONG).show();
        		}
			}
		});
		//*************************************************************************************************
		// Print User-defined character 
		printUserDefCharBtn = (Button)findViewById(R.id.wifi_print_userfont);
		printUserDefCharBtn.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				if(pos_wifi != null)
				{
					error_code = testprint.TestUserDefinedCharacter(pos_wifi, printMode);
					if(error_code != POS_SUCCESS)
					{
						Toast.makeText(WIFIActivity.this, "Failed to Print UserDefinedCharacter.",Toast.LENGTH_LONG).show();	
					}
				}
				else
				{
					Toast.makeText(WIFIActivity.this,
							"The connection to the printer has shut down, please click 'Connect Wi-Fi' button, try to connect to the printer.", Toast.LENGTH_LONG).show();
				}
				
			}
			
		});
		
		//***********************************************************************************************
		//FeedPaper
		printFeedLineBtn = (Button)findViewById(R.id.wifi_print_feed);
		printFeedLineBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if(pos_wifi != null)
				{
					error_code = testprint.TestFeedLine(pos_wifi, printMode);
	        		if(error_code != POS_SUCCESS)
	        		{
	        			Toast.makeText(WIFIActivity.this, "Failed to Feed Paper.",Toast.LENGTH_LONG).show();
	        		}		
				}
        		else 
        		{
					Toast.makeText(WIFIActivity.this,
							"The connection to the printer has shut down, please click 'Connect Wi-Fi' button, try to connect to the printer.", Toast.LENGTH_LONG).show();
				}	
			}
		});
		
		//*************************************************************************************************
		//CutPaper
		printCutPaperBtn = (Button)findViewById(R.id.wifi_print_cut);
		printCutPaperBtn.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				if(pos_wifi != null)
				{
					error_code = testprint.TestCutPaper(pos_wifi, printMode);
	        		if(error_code != POS_SUCCESS)
	        		{
	        			Toast.makeText(WIFIActivity.this, "Failed to Cut Paper.",Toast.LENGTH_LONG).show();
	        		}		
				}
        		else 
        		{
					Toast.makeText(WIFIActivity.this,
							"The connection to the printer has shut down, please click 'Connect Wi-Fi' button, try to connect to the printer.", Toast.LENGTH_LONG).show();
				}
				
			}
			
		});

		//*************************************************************************************************
		// Get Printer State
		queryStateBtn = (Button) findViewById(R.id.wifi_query_state);
		queryStateBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
		
				byte[] posStateTemp = new byte[1];
				int result;
				if(pos_state != null){
					result = testprint.POSNETQueryStatus(pos_state,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 {
						System.out.println("Get queryState error! result="+result);
						Toast.makeText(WIFIActivity.this, "Failed to read Data.",
								Toast.LENGTH_LONG).show();
					}				
				}else{
					Toast.makeText(WIFIActivity.this,
							"The connection to the printer has shut down, please click 'Connect Wi-Fi' button, try to connect to the printer.", 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();
//			}
			String str = lstDevices.get(arg2);
			
			String[] values = str.split("\\|");
			address = values[1];
			

			setTitle("IP::" + address);
			TextView tv = (TextView) findViewById(R.id.wifi_printer_ip);
			POSIP = address;
	//		setContentView(R.id.wifi_printer_ip);
			tv.setText(POSIP);

			// connect devices
			Toast.makeText(WIFIActivity.this, "Connection is establishing  £¬Please wait.",
					Toast.LENGTH_LONG).show();
			
			// Open device
			error_code = interface_wifi.OpenDevice(address, POSPORT);
			if(error_code != POS_SUCCESS){
				Toast.makeText(WIFIActivity.this, "Open Port Fail.", Toast.LENGTH_LONG).show();
				return;
			}else{
				if(pos_wifi != null){
					pos_wifi = null;
				}
				pos_wifi = new POSSDK(interface_wifi);
			}
			error_code = interface_state.OpenDevice(address, STATEPORT);
			if(error_code != POS_SUCCESS){
				Toast.makeText(WIFIActivity.this, "Open Port Fail.", Toast.LENGTH_LONG).show();
			}else{
				if(pos_state != null){
					pos_state = null;
				}
				pos_state = new POSSDK(interface_state);
			}
			
			if (error_code == POS_SUCCESS) {
				Toast.makeText(WIFIActivity.this, "Connection has been established £¬you can send the data.", Toast.LENGTH_LONG)
						.show();
				new CheckWriteSocketConnectionState().start();
			}else{
				Toast.makeText(WIFIActivity.this, "Failed to connect device, please try again.", Toast.LENGTH_LONG).show();
			}
		}
	}
	
	
	class CheckWriteSocketConnectionState extends Thread {

		public void run() {
			while (interface_wifi != null) {
				try {
					long currentTimeMillis = System.currentTimeMillis();
					if (currentTimeMillis - lastWriteTime > 60000){
						interface_wifi.CloseDevice();
	//					interface_wifi.OpenDevice(POSIP, POSPORT);
						updateLastWriteTime();
					}
				} catch (Exception e) {
					Toast.makeText(WIFIActivity.this,
							"The connection to the printer has shut down, please click 'Connect Wi-Fi' button, try to connect to the printer.",
							Toast.LENGTH_LONG).show();
				}
			}
		}
	}
	
	private void RefreshInfo(){
		lstDevices.clear(); // Empty list
		adtDevices.notifyDataSetChanged(); // Refresh the list
	}
	
	private void updateLastWriteTime()
	{
		lastWriteTime = System.currentTimeMillis();
	}
	
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		if (pos_wifi != null) {
			interface_wifi.CloseDevice();
			interface_wifi = null;
			pos_wifi = null;
		}
		if (pos_state != null) {
			interface_state.CloseDevice();
			interface_state = null;
			pos_state = null;
		}
		super.onDestroy();
	}
}
