package com.printsdksample;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.leon.lfilepickerlibrary.LFilePicker;
import com.yancy.imageselector.ImageConfig;
import com.yancy.imageselector.ImageSelector;
import com.yancy.imageselector.ImageSelectorActivity;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import HPRTAndroidSDK.HPRTPrinterHelper;
import HPRTAndroidSDK.IPort;
import HPRTAndroidSDK.PublicFunction;
import print.Print;
import print.WifiTool;

;

public class Activity_Main extends Activity 
{
	private Context thisCon=null;
	private BluetoothAdapter mBluetoothAdapter;
	private PublicFunction PFun=null;
	private PublicAction PAct=null;
	
	private Button btnWIFI=null;
	private Button btnBT=null;
	private Button btnUSB=null;
	private Button btnSerial=null;
	
	private Spinner spnPrinterList=null;
	private TextView txtTips=null;
	private Button btnOpenCashDrawer=null;
	private Button btnSampleReceipt=null;	
	private Button btn1DBarcodes=null;
	private Button btnQRCode=null;
	private Button btnPDF417=null;
	private Button btnCut=null;
	private Button btnPageMode=null;
	private Button btnImageManage=null;
	private Button btnGetRemainingPower=null;
	
	private EditText edtTimes=null;
	
	private ArrayAdapter arrPrinterList; 
	private String ConnectType="";
	private String PrinterName="";
	private String PortParam="";
	
	private UsbManager mUsbManager=null;	
	private UsbDevice device=null;
	private static final String ACTION_USB_PERMISSION = "com.PRINTSDKSample";
	private PendingIntent mPermissionIntent=null;
	private static IPort Printer=null;
	private static String[] PERMISSIONS_STORAGE = {
			"android.permission.READ_EXTERNAL_STORAGE",
			"android.permission.WRITE_EXTERNAL_STORAGE" };
	private static String[] wifi_PERMISSIONS={
			"android.permission.CHANGE_WIFI_STATE",
			"android.permission.ACCESS_WIFI_STATE"
	};
	String baudrate="";
	int REQUESTCODE_FROM_ACTIVITY = 1000;
	private ExecutorService executorService = Executors.newSingleThreadExecutor();

	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		setTitle(BuildConfig.VERSION_NAME);
		try
		{
			thisCon=this.getApplicationContext();
			
			btnWIFI = (Button) findViewById(R.id.btnWIFI);
			btnUSB = (Button) findViewById(R.id.btnUSB);
			btnBT = (Button) findViewById(R.id.btnBT);
			btnSerial = (Button) findViewById(R.id.btnSerial);
			
			//edtTimes = (EditText) findViewById(R.id.edtTimes);
			
			spnPrinterList = (Spinner) findViewById(R.id.spn_printer_list);	
			txtTips = (TextView) findViewById(R.id.txtTips);
			btnSampleReceipt = (Button) findViewById(R.id.btnSampleReceipt);
			btnOpenCashDrawer = (Button) findViewById(R.id.btnOpenCashDrawer);
			btn1DBarcodes = (Button) findViewById(R.id.btn1DBarcodes);
			btnQRCode = (Button) findViewById(R.id.btnQRCode);
			btnPDF417 = (Button) findViewById(R.id.btnPDF417);
			btnCut = (Button) findViewById(R.id.btnCut);
			btnPageMode = (Button) findViewById(R.id.btnPageMode);
			btnImageManage = (Button) findViewById(R.id.btnImageManage);
			btnGetRemainingPower = (Button) findViewById(R.id.btnGetRemainingPower);
					
			mPermissionIntent = PendingIntent.getBroadcast(thisCon, 0, new Intent(ACTION_USB_PERMISSION), 0);
	        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
			filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
			thisCon.registerReceiver(mUsbReceiver, filter);
			
			PFun=new PublicFunction(thisCon);
			PAct=new PublicAction(thisCon);
			InitSetting();
			InitCombox();
			this.spnPrinterList.setOnItemSelectedListener(new OnItemSelectedPrinter());
			//Enable Bluetooth
			EnableBluetooth();
			handler = new Handler(){
				@Override
				public void handleMessage(Message msg) {
					// TODO Auto-generated method stub
					super.handleMessage(msg);
					if (msg.what==1) {
						Toast.makeText(thisCon, "succeed", Toast.LENGTH_LONG).show();
						dialog.cancel();
					}else {
						Toast.makeText(thisCon, "failure", Toast.LENGTH_LONG).show();
						dialog.cancel();
					}
				}
			};
//			HPRTPrinterHelper.isWriteLog=true;
//			HPRTPrinterHelper.isHex=true;
		}
		catch (Exception e) 
		{			
			Log.e("HPRTSDKSample", (new StringBuilder("Activity_Main --> onCreate ")).append(e.getMessage()).toString());
		}
	}
	
	private void InitSetting()
	{
		String SettingValue="";
		SettingValue=PFun.ReadSharedPreferencesData("Codepage");
		if(SettingValue.equals(""))		
			PFun.WriteSharedPreferencesData("Codepage", "0,PC437(USA:Standard Europe)");			
		
		SettingValue=PFun.ReadSharedPreferencesData("Cut");
		if(SettingValue.equals(""))		
			PFun.WriteSharedPreferencesData("Cut", "0");	//
			
		SettingValue=PFun.ReadSharedPreferencesData("Cashdrawer");
		if(SettingValue.equals(""))			
			PFun.WriteSharedPreferencesData("Cashdrawer", "0");
					
		SettingValue=PFun.ReadSharedPreferencesData("Buzzer");
		if(SettingValue.equals(""))			
			PFun.WriteSharedPreferencesData("Buzzer", "0");
					
		SettingValue=PFun.ReadSharedPreferencesData("Feeds");
		if(SettingValue.equals(""))			
			PFun.WriteSharedPreferencesData("Feeds", "0");				
	}
	
	//add printer list
	private void InitCombox()
	{
		try
		{
			arrPrinterList = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item);
			String strSDKType=thisCon.getString(com.printsdksample.R.string.sdk_type);
			if(strSDKType.equals("all"))
				arrPrinterList=ArrayAdapter.createFromResource(this, R.array.printer_list_all, android.R.layout.simple_spinner_item);
			if(strSDKType.equals("mkt"))
				arrPrinterList=ArrayAdapter.createFromResource(this, R.array.printer_list_mkt, android.R.layout.simple_spinner_item);
			if(strSDKType.equals("mprint"))
				arrPrinterList=ArrayAdapter.createFromResource(this, R.array.printer_list_mprint, android.R.layout.simple_spinner_item);
			if(strSDKType.equals("sycrown"))
				arrPrinterList=ArrayAdapter.createFromResource(this, R.array.printer_list_sycrown, android.R.layout.simple_spinner_item);
			if(strSDKType.equals("mgpos"))
				arrPrinterList=ArrayAdapter.createFromResource(this, R.array.printer_list_mgpos, android.R.layout.simple_spinner_item);
			if(strSDKType.equals("ds"))
				arrPrinterList=ArrayAdapter.createFromResource(this, R.array.printer_list_ds, android.R.layout.simple_spinner_item);
			if(strSDKType.equals("cst"))
				arrPrinterList=ArrayAdapter.createFromResource(this, R.array.printer_list_cst, android.R.layout.simple_spinner_item);
			if(strSDKType.equals("other"))
				arrPrinterList=ArrayAdapter.createFromResource(this, R.array.printer_list_other, android.R.layout.simple_spinner_item);
			arrPrinterList.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			PrinterName=arrPrinterList.getItem(0).toString();
			spnPrinterList.setAdapter(arrPrinterList);
		}
		catch (Exception e) 
		{			
			Log.e("HPRTSDKSample", (new StringBuilder("Activity_Main --> InitCombox ")).append(e.getMessage()).toString());
		}
	}
	
	private class OnItemSelectedPrinter implements OnItemSelectedListener
	{				
		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,long arg3) 
		{
			PrinterName=arrPrinterList.getItem(arg2).toString();
//			CapturePrinterFunction();
//			GetPrinterProperty();
		}
		@Override
		public void onNothingSelected(AdapterView<?> arg0) 
		{
			// TODO Auto-generated method stub			
		}
	}
	
	//EnableBluetooth
	private boolean EnableBluetooth()
    {
        boolean bRet = false;
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if(mBluetoothAdapter != null)
        {
            if(mBluetoothAdapter.isEnabled())
                return true;
            mBluetoothAdapter.enable();
            try 
    		{
    			Thread.sleep(500);
    		} 
    		catch (InterruptedException e) 
    		{			
    			e.printStackTrace();
    		}
            if(!mBluetoothAdapter.isEnabled())
            {
                bRet = true;
                Log.d("PRTLIB", "BTO_EnableBluetooth --> Open OK");
            }
        } 
        else
        {
        	Log.d("HPRTSDKSample", (new StringBuilder("Activity_Main --> EnableBluetooth ").append("Bluetooth Adapter is null.")).toString());
        }
        return bRet;
    }
	
	//call back by scan bluetooth printer
	@Override  
  	protected void onActivityResult(int requestCode, int resultCode, final Intent data)  
  	{  
  		try
  		{  		
  			String strIsConnected;
	  		switch(resultCode)
	  		{
	  			case Print.ACTIVITY_CONNECT_BT:
	  				strIsConnected=data.getExtras().getString("is_connected");
	  	        	if (strIsConnected.equals("NO")) {
	  	        		txtTips.setText(thisCon.getString(R.string.activity_main_scan_error));	  	        		
  	                	return;
	  	        	}
	  	        	else {
	  						txtTips.setText(thisCon.getString(R.string.activity_main_connected));
	  					return;
	  	        	}		  	        	
	  			case Print.ACTIVITY_CONNECT_WIFI:
	  				strIsConnected=data.getExtras().getString("is_connected");
	  	        	if (strIsConnected.equals("NO")) {
	  	        		txtTips.setText(thisCon.getString(R.string.activity_main_scan_error));	  	        		
  	                	return;
	  	        	}
	  	        	else {
						txtTips.setText(thisCon.getString(R.string.activity_main_connected));
	  					return;
	  	        	}
	  			case Print.ACTIVITY_PRNFILE:
//	  		    	PAct.LanguageEncode();
	  		    	PAct.BeforePrintAction();
	  				String strPRNFile=data.getExtras().getString("FilePath");
	  				System.out.println(strPRNFile);
					Print.PrintBinaryFile(strPRNFile);
	  				PAct.AfterPrintAction();
	  				return;
				case RESULT_OK:
					if (requestCode == REQUESTCODE_FROM_ACTIVITY) {
						List<String> list = data.getStringArrayListExtra("paths");
						String mFilename = list.get(0);
						File file = new File(mFilename);
						List<Bitmap> bitmaps = HPRTPrinterHelper.PrintPDF(thisCon, file, "1", 384);
						Print.PrintBitmap(bitmaps.get(0),1,0);
						return;
					}else if(requestCode==ImageSelector.IMAGE_REQUEST_CODE){
						setPrintDialog(data);
						return;
					}
  			}
  		}
  		catch(Exception e)
  		{
  			Log.e("HPRTSDKSample", (new StringBuilder("Activity_Main --> onActivityResult ")).append(e.getMessage()).toString());
  		}
        super.onActivityResult(requestCode, resultCode, data);  
  	}

	private void setPrintDialog(Intent data) {
		List<String> path = data.getStringArrayListExtra(ImageSelectorActivity.EXTRA_RESULT);
		final Bitmap bmp = BitmapFactory.decodeFile(path.get(0));
		if (bmp==null){
			Toast.makeText(thisCon,"Image error",Toast.LENGTH_SHORT).show();
			return;
		}
		AlertDialogUtil alertDialogUtil = new AlertDialogUtil(Activity_Main.this);
		AlertDialog.Builder builder = alertDialogUtil.setAlertDialog();
		View view = alertDialogUtil.setViewID(R.layout.item_print);
		final RadioButton rbInch3 =  view.findViewById(R.id.rb_inch3);
		final RadioButton rbLzoNo =  view.findViewById(R.id.rb_lzo_no);
		final RadioButton rbZero =  view.findViewById(R.id.rb_zero);
		final RadioButton rbShake =  view.findViewById(R.id.rb_shake);
		final RadioButton rbBlackW =  view.findViewById(R.id.rb_bw);
		final EditText edLight =  view.findViewById(R.id.ed_light);
		builder.setNegativeButton(R.string.activity_wifi_btncancel, null);
		builder.setPositiveButton(R.string.activity_global_print, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialogInterface, int i) {
				String strLight = edLight.getText().toString();
				if (TextUtils.isEmpty(strLight)||strLight.length()>4||!Utility.isInteger(strLight)||Integer.valueOf(strLight)<-100||Integer.valueOf(strLight)>100){
					Toast.makeText(thisCon,R.string.activity_main_light_message,Toast.LENGTH_SHORT).show();
					return;
				}
				printImage(bmp, Integer.valueOf(strLight), rbInch3.isChecked()?576:384, !rbZero.isChecked(),rbShake.isChecked()?1:(rbBlackW.isChecked()?0:2),!rbLzoNo.isChecked());
			}
		});
		builder.show();
	}
	public void printImage(final Bitmap bitmap,final int light,final int size,final boolean isRotate,final int sype, final boolean isLzo){
		dialog = new ProgressDialog(Activity_Main.this);
		dialog.setMessage("Printing.....");
		dialog.setProgress(100);
		dialog.show();
		executorService.execute(new Runnable() {
			@Override
			public void run() {
				PAct.BeforePrintAction();
				Bitmap bitmapPrint=bitmap;
				if (isRotate)
					bitmapPrint = Utility.Tobitmap90(bitmapPrint);
				bitmapPrint=Utility.Tobitmap(bitmapPrint,size,Utility.getHeight(size,bitmapPrint.getWidth(),bitmapPrint.getHeight()));
				int printImage=0;
				try {
					if (!isLzo)
						printImage=Print.PrintBitmap(bitmapPrint,sype,light);
					else
						printImage=Print.PrintBitmapLZO(bitmapPrint,sype,light);
					if (printImage>=0) {
						handler.sendEmptyMessage(1);
					}else {
						handler.sendEmptyMessage(0);
					}
				} catch (Exception e){
					handler.sendEmptyMessage(0);
				}
				bitmap.recycle();
				bitmapPrint.recycle();
				PAct.AfterPrintAction();
			}
		});
	}

	@SuppressLint("NewApi")
	public void onClickConnect(View view) 
	{		
    	if (!checkClick.isClickEvent()) return;
    	
    	try
    	{
	    	if(view.getId()==R.id.btnBT)
	    	{
                if (Build.VERSION.SDK_INT >= 23) {
                    //校验是否已具有模糊定位权限
                    if (ContextCompat.checkSelfPermission(Activity_Main.this,
                            android.Manifest.permission.ACCESS_COARSE_LOCATION)
                            != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(Activity_Main.this,
                                new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION},
                                100);
                    } else {
                        //具有权限
                        ConnectType="Bluetooth";
                        Intent serverIntent = new Intent(thisCon,Activity_DeviceList.class);
                        startActivityForResult(serverIntent, Print.ACTIVITY_CONNECT_BT);
                        return;
                    }
                } else {
                    //系统不高于6.0直接执行
                    ConnectType="Bluetooth";
                    Intent serverIntent = new Intent(thisCon,Activity_DeviceList.class);
                    startActivityForResult(serverIntent, Print.ACTIVITY_CONNECT_BT);
                }
				return;
	    	}
	    	else if(view.getId()==R.id.btnWIFI)
	    	{
				Utility.checkBlueboothPermission(Activity_Main.this, android.Manifest.permission.ACCESS_WIFI_STATE, wifi_PERMISSIONS, new Utility.Callback() {
					@Override
					public void permit() {
						setWifiDialog();
						return;
					}

					@Override
					public void pass() {
						setWifiDialog();
						return;
					}
				});

	    	}
	    	else if(view.getId()==R.id.btnUSB)
	    	{
	    		ConnectType="USB";							
				//USB not need call "iniPort"
				mUsbManager = (UsbManager) thisCon.getSystemService(Context.USB_SERVICE);				
		  		HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();  		
		  		Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
		  		
		  		boolean HavePrinter=false;		  
		  		while(deviceIterator.hasNext())
		  		{
		  		    device = deviceIterator.next();
		  		    int count = device.getInterfaceCount();
		  		    for (int i = 0; i < count; i++) 
		  	        {
		  		    	UsbInterface intf = device.getInterface(i);
		  	            if (intf.getInterfaceClass() == 7)
		  	            {
							Log.d("PRINT_TAG", "vendorID--" + device.getVendorId() + "ProductId--" + device.getProductId());
//							if (device.getVendorId()==8401&&device.getProductId()==28680){
//								Log.d("PRINT_TAG","123");
								HavePrinter=true;
								mUsbManager.requestPermission(device, mPermissionIntent);
//							}
		  	            }
		  	        }
		  		}
		  		if(!HavePrinter)
		  			txtTips.setText(thisCon.getString(R.string.activity_main_connect_usb_printer));	
	    	}
	    	else if(view.getId()==R.id.btnSerial){
	    		ConantSerial(Activity_Main.this);
	    	}
    	}
		catch (Exception e) 
		{			
			Log.e("HPRTSDKSample", (new StringBuilder("Activity_Main --> onClickConnect "+ConnectType)).append(e.getMessage()).toString());
		}
    }
		   			
	private BroadcastReceiver mUsbReceiver = new BroadcastReceiver() 
	{
	    public void onReceive(Context context, Intent intent) 
	    {
	    	try
	    	{
		        String action = intent.getAction();	       
		        if (ACTION_USB_PERMISSION.equals(action))
		        {
			        synchronized (this) 
			        {		        	
			            device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
				        if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false))
				        {			 
				        	if(Print.PortOpen(thisCon,device)!=0)
							{					
								txtTips.setText(thisCon.getString(R.string.activity_main_connecterr));
			                	return;
							}
				        	else
				        		txtTips.setText(thisCon.getString(R.string.activity_main_connected));
				        		
				        }		
				        else
				        {			        	
				        	return;
				        }
			        }
			    }
				if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action))
				{
					device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
					if (device != null)
					{
						int count = device.getInterfaceCount();
						for (int i = 0; i < count; i++)
						{
							UsbInterface intf = device.getInterface(i);
							//Class ID 7代表打印机
							if (intf.getInterfaceClass() == 7)
							{
								Print.PortClose();
								txtTips.setText(R.string.activity_main_tips);
							}
						}
					}
				}
			}
	    	catch (Exception e) 
	    	{
	    		Log.e("HPRTSDKSample", (new StringBuilder("Activity_Main --> mUsbReceiver ")).append(e.getMessage()).toString());
	    	}
		}
	};
	private Handler handler;
	private ProgressDialog dialog;
	
	public void onClickClose(View view) 
	{
    	if (!checkClick.isClickEvent()) return;
    	
    	try
    	{

			Print.PortClose();

			this.txtTips.setText(R.string.activity_main_tips);
			return;	
    	}
		catch (Exception e) 
		{			
			Log.e("HPRTSDKSample", (new StringBuilder("Activity_Main --> onClickClose ")).append(e.getMessage()).toString());
		}
    }
	
	public void onClickbtnSetting(View view) 
	{
    	if (!checkClick.isClickEvent()) return;
    	
    	try
    	{
    		startActivity(new Intent(Activity_Main.this, Activity_Setting.class));
    	}
		catch (Exception e) 
		{			
			Log.e("HPRTSDKSample", (new StringBuilder("Activity_Main --> onClickClose ")).append(e.getMessage()).toString());
		}
    }
	
	public void onClickDo(View view) 
	{
		if (!checkClick.isClickEvent()) return;
		
		if(!Print.IsOpened())
		{
			Toast.makeText(thisCon, thisCon.getText(R.string.activity_main_tips), Toast.LENGTH_SHORT).show();				
			return;
		}
		    	    	
    	if(view.getId()==R.id.btnGetStatus)
    	{
    		Intent myIntent = new Intent(this, Activity_Status.class);
        	myIntent.putExtra("StatusMode", PrinterProperty.StatusMode);
        	startActivityFromChild(this, myIntent, 0);
    	}
    	else if(view.getId()==R.id.btnOpenCashDrawer)
    	{
    		Intent myIntent = new Intent(this, Activity_Cashdrawer.class);
        	startActivityFromChild(this, myIntent, 0);
    	}
    	else if(view.getId()==R.id.btnSampleReceipt)
    	{
    		PrintSampleReceipt();
    	}
    	else if(view.getId()==R.id.btn1DBarcodes)
    	{
    		Intent myIntent = new Intent(this, Activity_1DBarcodes.class);    		
        	startActivityFromChild(this, myIntent, 0);
    	}
    	else if(view.getId()==R.id.btnCut)
    	{
    		Intent myIntent = new Intent(this, Activity_Cut.class);    	       
        	startActivityFromChild(this, myIntent, 0);
    	}
    	else if(view.getId()==R.id.btnTextFormat)
    	{
    		Intent myIntent = new Intent(this, Activity_TextFormat.class);
        	startActivityFromChild(this, myIntent, 0);
    	}
    	else if(view.getId()==R.id.btnPrintImageFile)
    	{

			Utility.checkBlueboothPermission(Activity_Main.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE, PERMISSIONS_STORAGE, new Utility.Callback() {
				@Override
				public void permit() {
					setImageDialog();
				}

				@Override
				public void pass() {
					setImageDialog();
				}
			});
		}
    	else if(view.getId()==R.id.btnPrintCardRead) {
			Activity_Magnetic_Card.startActivity(this);
    	}
    	else if(view.getId()==R.id.btnPageMode)
    	{
    		Utility.checkBlueboothPermission(Activity_Main.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE, PERMISSIONS_STORAGE, new Utility.Callback() {
				@Override
				public void permit() {
					printPDF();
				}

				public void pass() {
					printPDF();
				}
			});
    	}
    	else if(view.getId()==R.id.btnQRCode)
    	{
    		Intent myIntent = new Intent(this, Activity_QRCode.class);
        	startActivityFromChild(this, myIntent, 0);
    	}    	
    	else if(view.getId()==R.id.btnPDF417)
    	{
    		Intent myIntent = new Intent(this, Activity_PDF417.class);
    		startActivityFromChild(this, myIntent, 0);
    	}    	
    	else if(view.getId()==R.id.btnImageManage)
    	{
			Utility.checkBlueboothPermission(Activity_Main.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE, PERMISSIONS_STORAGE, new Utility.Callback() {
				@Override
				public void permit() {
					Intent myIntent = new Intent(Activity_Main.this, Activity_Image_Manage.class);
					startActivityFromChild(Activity_Main.this, myIntent, 0);
				}

				public void pass() {
					Intent myIntent = new Intent(Activity_Main.this, Activity_Image_Manage.class);
					startActivityFromChild(Activity_Main.this, myIntent, 0);
				}
			});
		}else if(view.getId()==R.id.btnPrintTestPage) {
			PrintTestPage();
//			printTest();
    	}
    }

	private void printTest() {
		try{
			HPRTPrinterHelper.ReadData(5000);
		}catch (Exception e){}
	}

	private void printPDF() {
		new LFilePicker()
				.withActivity(this)
				.withRequestCode(REQUESTCODE_FROM_ACTIVITY)
				.withStartPath(Environment.getExternalStorageDirectory().getAbsolutePath())
				.withTitle(getResources().getString(R.string.activity_esc_function_btnpagemode))
				.withMutilyMode(false)
				.withBackgroundColor("#000000")
				.withTitleColor("#ffffff")
				.withFileFilter(new String[]{".PDF", ".pdf"})
				.start();
	}

	private void setImageDialog() {
//		AlertDialog.Builder builder = new AlertDialog.Builder(Activity_Main.this);
//		builder.setItems(new String[]{getString(R.string.activity_image_common),getString(R.string.activity_image_lzo)}, new DialogInterface.OnClickListener() {
//			@Override
//			public void onClick(DialogInterface dialog, int which) {
//				switch(which){
//				    case 0:
//						Activity_PRNFile.setStartActivity(Activity_Main.this,android.os.Environment.getExternalStorageDirectory().getAbsolutePath(),"jpg,gif,png,bmp,pdf,",Print.ACTIVITY_IMAGE_FILE);
//				        break;
//				    case 1:
//						Activity_PRNFile.setStartActivity(Activity_Main.this,android.os.Environment.getExternalStorageDirectory().getAbsolutePath(),"jpg,gif,png,bmp,pdf,",2);
//				        break;
//				    default:
//				        break;
//				}
//			}
//		});
//		builder.show();
		ImageConfig imageConfig
				= new ImageConfig.Builder(new GlideLoader())
				.steepToolBarColor(getResources().getColor(R.color.black))
				.titleBgColor(getResources().getColor(R.color.black))
				.titleSubmitTextColor(getResources().getColor(R.color.white))
				.titleTextColor(getResources().getColor(R.color.white))
				// 开启单选   （默认为多选）
				.singleSelect()
				// 开启拍照功能 （默认关闭）
//                .showCamera()
				// 拍照后存放的图片路径（默认 /temp/picture） （会自动创建）
//                .filePath("/ImageSelector/Pictures")
				.build();


		ImageSelector.open(Activity_Main.this, imageConfig);   // 开启图片选择器
	}
	public class GlideLoader implements com.yancy.imageselector.ImageLoader {

		@Override
		public void displayImage(Context context, String path, ImageView imageView) {
			Glide.with(context)
					.load(path)
					.placeholder(com.yancy.imageselector.R.mipmap.imageselector_photo)
					.centerCrop()
					.into(imageView);
		}

	}
	public void PrintTestPage() 
	{    	
    	try
    	{    		    		
//    		PAct.LanguageEncode();
    		PAct.BeforePrintAction();  
    		
    		String strPrintText="Print SDK Sample!";
			Print.PrintText(thisCon.getString(R.string.activity_main_originalsize) + strPrintText+"\n",0,0,0);
			Print.PrintText(thisCon.getString(R.string.activity_main_heightsize) + strPrintText+"\n",0,16,0);
			Print.PrintText(thisCon.getString(R.string.activity_main_widthsize) + strPrintText+"\n",0,32,0);
			Print.PrintText(thisCon.getString(R.string.activity_main_heightwidthsize) + strPrintText+"\n",0,48,0);
			Print.PrintText(thisCon.getString(R.string.activity_main_bold) + strPrintText+"\n",0,2,0);
			Print.PrintText(thisCon.getString(R.string.activity_main_underline) + strPrintText+"\n",0,4,0);
			Print.PrintText(thisCon.getString(R.string.activity_main_minifront) + strPrintText+"\n",0,1,0);

			//"UPC-A,UPC-E,EAN8,EAN13,CODE39,ITF,CODEBAR,CODE128,CODE93,QRCODE"
				Barcode_BC_UPCA();
				Barcode_BC_UPCE();
				Barcode_BC_EAN8();
				Barcode_BC_EAN13();
				Barcode_BC_CODEBAR();
				Barcode_BC_ITF();
			PAct.AfterPrintAction();
    	}
		catch (Exception e) 
		{
			Log.e("HPRTSDKSample", (new StringBuilder("Activity_Main --> onClickWIFI ")).append(e.getMessage()).toString());
		}
    }

	private int Barcode_BC_UPCA() throws Exception
	{
		Print.PrintText("BC_UPCA:\n");
		return Print.PrintBarCode(Print.BC_UPCA,
		 		 "075678164125");
	}
	
	private int Barcode_BC_UPCE() throws Exception
	{
		Print.PrintText("BC_UPCE:\n");
		return Print.PrintBarCode(Print.BC_UPCE,
	 		 "01227000009");//04252614 
	}
	
	private int Barcode_BC_EAN8() throws Exception
	{
		Print.PrintText("BC_EAN8:\n");
		return Print.PrintBarCode(Print.BC_EAN8,
	 		 "04210009");		
	}
	
	private int Barcode_BC_EAN13() throws Exception
	{
		Print.PrintText("BC_EAN13:\n");
		return Print.PrintBarCode(Print.BC_EAN13,
		 		 "6901028075831");		
	}
	
	private int Barcode_BC_CODE93() throws Exception
	{
		Print.PrintText("BC_CODE93:\n");
		return Print.PrintBarCode(Print.BC_CODE93,
	 		 "TEST93");		
	}
	
	private int Barcode_BC_CODE39() throws Exception
	{
		Print.PrintText("BC_CODE39:\n");
		return Print.PrintBarCode(Print.BC_CODE39,
	 		 "123456789");		
	}
	
	private int Barcode_BC_CODEBAR() throws Exception
	{
		Print.PrintText("BC_CODEBAR:\n");
		return Print.PrintBarCode(Print.BC_CODEBAR,
	 		 "A40156B");		
	}
	
	private int Barcode_BC_ITF() throws Exception
	{
		Print.PrintText("BC_ITF:\n");
		return Print.PrintBarCode(Print.BC_ITF,
			"123456789012");		
	}
	
	private int Barcode_BC_CODE128() throws Exception
	{
		Print.PrintText("BC_CODE128:\n");
		return Print.PrintBarCode(Print.BC_CODE128,
	 		 "{BS/N:{C\014\042\070\116{A3");	// decimal 1234 = octonary 1442		
	}

	private void CapturePrinterFunction()
	{
		try
		{
			int[] propType=new int[1];
			byte[] Value=new byte[500];
			int[] DataLen=new int[1];
			String strValue="";
			boolean isCheck=false;
			
			int iRtn=Print.CapturePrinterFunction(Print.MODEL_PROPERTY_KEY_BEEP, propType, Value,DataLen);
			if(iRtn!=0)
				return;			
			PrinterProperty.Buzzer=(Value[0]==0?false:true);
			
			iRtn=Print.CapturePrinterFunction(Print.MODEL_PROPERTY_KEY_CUT, propType, Value,DataLen);
			if(iRtn!=0)
				return;			
			PrinterProperty.Cut=(Value[0]==0?false:true);
			btnCut.setVisibility((PrinterProperty.Cut?View.VISIBLE:View.GONE));
			
			iRtn=Print.CapturePrinterFunction(Print.MODEL_PROPERTY_KEY_DRAWER, propType, Value,DataLen);
			if(iRtn!=0)
				return;		
			PrinterProperty.Cashdrawer=(Value[0]==0?false:true);
			btnOpenCashDrawer.setVisibility((PrinterProperty.Cashdrawer?View.VISIBLE:View.GONE));
			
			iRtn=Print.CapturePrinterFunction(Print.MODEL_PROPERTY_KEY_BARCODE, propType, Value,DataLen);
			if(iRtn!=0)
				return;						
			PrinterProperty.Barcode=new String(Value);
			isCheck=PrinterProperty.Barcode.replace("QRCODE", "").replace("PDF417", "").replace(",,", ",").replace(",,", ",").length()>0;
			btn1DBarcodes.setVisibility((isCheck?View.VISIBLE:View.GONE));								
			isCheck = PrinterProperty.Barcode.contains("QRCODE");
			btnQRCode.setVisibility((isCheck?View.VISIBLE:View.GONE));
			btnPDF417.setVisibility((PrinterProperty.Barcode.indexOf("PDF417") != -1?View.VISIBLE:View.GONE));
			
			iRtn=Print.CapturePrinterFunction(Print.MODEL_PROPERTY_KEY_PAGEMODE, propType, Value,DataLen);
			if(iRtn!=0)
				return;		
			PrinterProperty.Pagemode=(Value[0]==0?false:true);
			if (PrinterName.equals("MLP2")) {
				btnPageMode.setVisibility(View.VISIBLE);
			}else {
				btnPageMode.setVisibility((PrinterProperty.Pagemode?View.VISIBLE:View.GONE));
			}
			
			iRtn=Print.CapturePrinterFunction(Print.MODEL_PROPERTY_KEY_GET_REMAINING_POWER, propType, Value,DataLen);
			if(iRtn!=0)
				return;	
			PrinterProperty.GetRemainingPower=(Value[0]==0?false:true);
			btnGetRemainingPower.setVisibility((PrinterProperty.GetRemainingPower?View.VISIBLE:View.GONE));
			
			iRtn=Print.CapturePrinterFunction(Print.MODEL_PROPERTY_CONNECT_TYPE, propType, Value,DataLen);
			if(iRtn!=0)
				return;	
			PrinterProperty.ConnectType=(Value[1]<<8)+Value[0];
			btnWIFI.setVisibility(((PrinterProperty.ConnectType&1)==0?View.GONE:View.VISIBLE));
			btnUSB.setVisibility(((PrinterProperty.ConnectType&16)==0?View.GONE:View.VISIBLE));
			btnBT.setVisibility(((PrinterProperty.ConnectType&32)==0?View.GONE:View.VISIBLE));
			
			iRtn=Print.CapturePrinterFunction(Print.MODEL_PROPERTY_KEY_PRINT_RECEIPT, propType, Value,DataLen);
			if(iRtn!=0)
				return;			
			PrinterProperty.SampleReceipt=(Value[0]==0?false:true);
			btnSampleReceipt.setVisibility((PrinterProperty.SampleReceipt?View.VISIBLE:View.GONE));							
		}
		catch(Exception e)
		{
			Log.e("HPRTSDKSample", (new StringBuilder("Activity_Main --> CapturePrinterFunction ")).append(e.getMessage()).toString());
		}
	}
	
	private void GetPrinterProperty()
	{
		try
		{
			int[] propType=new int[1];
			byte[] Value=new byte[500];
			int[] DataLen=new int[1];
			String strValue="";			
			int iRtn=0;
			
			iRtn=Print.CapturePrinterFunction(Print.MODEL_PROPERTY_KEY_STATUS_MODEL, propType, Value,DataLen);
			if(iRtn!=0)
				return;			
			PrinterProperty.StatusMode=Value[0];
			
			if(PrinterProperty.Cut)
			{
				iRtn=Print.CapturePrinterFunction(Print.MODEL_PROPERTY_KEY_CUT_SPACING, propType, Value,DataLen);
				if(iRtn!=0)
					return;			
				PrinterProperty.CutSpacing=Value[0];				
			}
			else
			{
				iRtn=Print.CapturePrinterFunction(Print.MODEL_PROPERTY_KEY_TEAR_SPACING, propType, Value,DataLen);
				if(iRtn!=0)
					return;		
				PrinterProperty.TearSpacing=Value[0];				
			}	
			
			if(PrinterProperty.Pagemode)
			{
				iRtn=Print.CapturePrinterFunction(Print.MODEL_PROPERTY_KEY_PAGEMODE_AREA, propType, Value,DataLen);
				if(iRtn!=0)
					return;			
				PrinterProperty.PagemodeArea=new String(Value).trim();				
			}
			Value=new byte[500];
			iRtn=Print.CapturePrinterFunction(Print.MODEL_PROPERTY_KEY_WIDTH, propType, Value,DataLen);
			if(iRtn!=0)
				return;			
			PrinterProperty.PrintableWidth=(int)(Value[0] & 0xFF | ((Value[1] & 0xFF) <<8));
		}
		catch(Exception e)
		{
			Log.e("HPRTSDKSample", (new StringBuilder("Activity_Main --> CapturePrinterFunction ")).append(e.getMessage()).toString());
		}
	}
	
	private void PrintSampleReceipt()
	{
		executorService.execute(new Runnable() {
			@Override
			public void run() {
				try
				{
					Print.WriteData(new byte[]{0x1b,0x40});
					PAct.LanguageEncode();
//					InputStream open = getResources().getAssets().open("test01.jpg");
//					Bitmap bitmap = BitmapFactory.decodeStream(open);
//					Print.PrintBitmap(bitmap,  (byte)1, (byte)0,200);
					PAct.BeforePrintAction();
					String[] ReceiptLines = getResources().getStringArray(R.array.activity_main_sample_2inch_receipt);
					for(int i=0;i<ReceiptLines.length;i++)
						Print.PrintText(ReceiptLines[i]);
					PAct.AfterPrintAction();
//					InputStream open2 = getResources().getAssets().open("test02.png");
//					Bitmap bitmap2 = BitmapFactory.decodeStream(open2);
//					Print.PrintBitmap(bitmap2,  (byte)1, (byte)0,200);
//					HPRTPrinterHelper.SelectCharacterFont((byte) 1);
//					PublicFunction PFunz=new PublicFunction(Main4Activity.this);
//					String sLanguage="Iran"; String sLEncode="iso-8859-6";
//					int intLanguageNum=56; sLEncode=PFunz.getLanguageEncode(sLanguage);
//					intLanguageNum= PFunz.getCodePageIndex(sLanguage); HPRTPrinterHelper.SetCharacterSet((byte)intLanguageNum);
//					HPRTPrinterHelper.LanguageEncode=sLEncode;
					//HPRTPrinterHelper.SetCharacterSet Returns -3 HPRTPrinterHelper.PrintText("این یک پیام برای تست میباشد.\r\n");
					//SDK下发指令设置codepage
//					HPRTPrinterHelper.SetCharacterSet((byte)56);
//					//设置编码
//					HPRTPrinterHelper.LanguageEncode="iso-8859-6";
//					HPRTPrinterHelper.PrintText("این یک پیام برای تست میباشد.\r\n");

				}
				catch(Exception e)
				{
					Log.e("HPRTSDKSample", (new StringBuilder("Activity_Main --> PrintSampleReceipt ")).append(e.getMessage()).toString());
				}
			}
		});
	}
	private void ConantSerial(Context context){
		AlertDialog.Builder builder=new AlertDialog.Builder(context);
		View inflate = LayoutInflater.from(context).inflate(R.layout.item_serial_dialog, null);
		final Spinner sp_serial_baudrate = (Spinner) inflate.findViewById(R.id.sp_serial_baudrate);
		final String[] sList=new String[]{"9600","14400","19200","115200"};
		arrPrinterList=new ArrayAdapter<String>(Activity_Main.this,android.R.layout.simple_spinner_item,sList);
		sp_serial_baudrate.setAdapter(arrPrinterList);
		sp_serial_baudrate.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				baudrate=sList[position];
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {

			}
		});
		final EditText ed_serial_port = (EditText) inflate.findViewById(R.id.ed_serial_port);
		builder.setPositiveButton(getResources().getString(R.string.activity_wifi_btnconnect), new AlertDialog.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				String port = ed_serial_port.getText().toString();
				if ("".equals(baudrate)) {
					Toast.makeText(getApplicationContext(), getString(R.string.serial_dialog_nobaudrate),Toast.LENGTH_LONG).show();
					return;
				}
				if ("".equals(port)) {
					Toast.makeText(getApplicationContext(), getString(R.string.serial_dialog_noport), Toast.LENGTH_LONG).show();
					return;
				}
				try {
					int portOpen = Print.PortOpen(thisCon,"Serial,"+port+","+baudrate);
					if (portOpen==-1) {
						txtTips.setText(thisCon.getString(R.string.activity_main_connecterr));	  
					}else {
						txtTips.setText(thisCon.getString(R.string.activity_main_connected));	
					}
				} catch (Exception e) {
					txtTips.setText(thisCon.getString(R.string.activity_main_connecterr));	  
				}
			}
		});
		builder.setNegativeButton(getString(R.string.activity_wifi_btncancel), null);
		builder.setView(inflate);
		builder.show();
	}
	private void setWifiDialog(){
		AlertDialog.Builder builder = new AlertDialog.Builder(Activity_Main.this);
		String[] str=new String[]{getString(R.string.wifi_select_ip_connection),getString(R.string.wifi_select_udp_connection)};
		builder.setItems(str, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				switch(which){
					case 0:
						ConnectType="WiFi";
						Intent serverIntent = new Intent(thisCon,Activity_Wifi.class);
						serverIntent.putExtra("PN", PrinterName);
						startActivityForResult(serverIntent, Print.ACTIVITY_CONNECT_WIFI);
						break;
					case 1:
						connectionUDP();
						break;
					default:
						break;
				}
			}
		});
		builder.show();
	}

	private void connectionUDP() {
		if(!WifiTool.isWifi(thisCon)){
			Toast.makeText(thisCon,"please connection wifi",Toast.LENGTH_SHORT).show();
			return;
		}
		startActivityForResult(new Intent(Activity_Main.this,Activity_UDP.class),100);
	}
	private void printTable(){
		try
		{
			Print.Initialize();//初始化
			Print.setPrintResolution(203,203);
			Print.SelectPageMode();//页模式
			Print.SetPageModePrintArea(0,0,640,1440);//区域(起始x，起始y，宽，高)
			Print.SetPageModePrintDirection(3);//方向（0：0度，1：90度，2：180度，3：270度）
			Print.SetPageModeAbsolutePosition(362,48);//横坐标 纵坐标
			Print.SetCharacterSize(17);//字体
			Print.PrintText("北京锦纶国际物流托运单");
			Print.SetPageModeAbsolutePosition(01,72);
			Print.SetCharacterSize((byte)0);
			Print.PrintText("货号：济南171117-北京001-1                 2017年11月17日");

			Print.SetPageModeAbsolutePosition(1088,72);
			Print.SetCharacterSize((byte)0);
			Print.PrintText("票号：100503446");
			Print.PrintPageRectangle(0,80,1280,480,2);//矩形框（起始x，起始Y，终点x，终点Y，线条宽度）
			Print.SetPageModeAbsolutePosition(16,120);
			Print.SetCharacterSize((byte)0);
			Print.PrintText("收 货 人      245        电 话         2452245           货 名          2         重 量           0");
			Print.PrintPageLine(0, 128, 1280, 128, 2);//线条（起始x，起始Y，终点x，终点Y，线条宽度）
			Print.SetPageModeAbsolutePosition(16,168);
			Print.SetCharacterSize((byte)0);
			Print.PrintText("收 货 人      2452       电 话         2452245           件 数          2         体 积           0");
			Print.PrintPageLine(0, 176, 1280, 176, 2);
			Print.SetPageModeAbsolutePosition(16,216);
			Print.SetCharacterSize((byte)0);
			Print.PrintText(" 提 付    现 付  回单付   货款扣   返 款   代收货款    手续费       运货费       保价         中转费");
			Print.PrintPageLine(0, 224, 1280, 224, 2);
			Print.SetPageModeAbsolutePosition(16,264);
			Print.SetCharacterSize((byte)0);
			Print.PrintText("   2        0      0       0        0        5           回：1          0           0           0");
			Print.PrintPageLine(0, 272, 1280, 272, 2);
			Print.SetPageModeAbsolutePosition(16,312);
			Print.SetCharacterSize((byte)0);
			Print.PrintText(" 会员号                   帐 号                                    到站合计               7");
			Print.PrintPageLine(0, 320, 1280, 320, 2);
			Print.SetPageModeAbsolutePosition(8,360);
			Print.SetCharacterSize((byte)0);
			Print.PrintText("委托单号                 回单要求                                   交货方式              自提");
			Print.PrintPageLine(0, 368, 1280, 368, 2);
			Print.SetPageModeAbsolutePosition(8,408);
			Print.SetCharacterSize((byte)0);
			Print.PrintText("委托地址   城环城： 五方： 西部： 神龙丰  56209689/87561903          客户签名");
			Print.PrintPageLine(0, 416, 1280, 416, 2);
			Print.SetPageModeAbsolutePosition(8,456);
			Print.SetCharacterSize((byte)0);
			Print.PrintText("到货地址   济南市老屯汽配城北门3#  0531-82533880");
			Print.PrintPageLine(0, 464, 1280, 464, 2);
			Print.SetPageModeAbsolutePosition(4,496);
			Print.SetCharacterSize((byte)0);
			Print.PrintText("托运人须知：");
			Print.SetPageModeAbsolutePosition(904,504);
			Print.SetCharacterSize((byte)0);
			Print.PrintText("备 注");
			Print.PrintPageLine(880, 520, 1280, 520, 2);
			Print.SetPageModeAbsolutePosition(904,544);
			Print.SetCharacterSize((byte)0);
			Print.PrintText("操作员：北京10：40：37");
			Print.PrintPageLine(128, 80, 128, 464, 2);
			Print.PrintPageLine(208, 176, 208, 272, 2);
			Print.PrintPageLine(288, 80, 288, 368, 2);
			Print.PrintPageLine(416, 80, 416, 368, 2);
			Print.PrintPageLine(496, 176, 496, 272, 2);
			Print.PrintPageLine(656, 80, 656, 272, 2);
			Print.PrintPageLine(800, 80, 800, 416, 2);
			Print.PrintPageLine(968, 80, 968, 416, 2);
			Print.PrintPageLine(1120, 80, 1120, 272, 2);
			Print.PrintPageLine(880, 464, 880, 560, 2);
			Print.PrintPageLine(968, 464, 968, 520, 2);
			Print.SetPageModePrintDirection(0);
			Print.SetPageModeAbsolutePosition(288,1350);
			Print.PrintBarCode(72, "123456789", 3, 50, 0, 2);
//			HPRTPrinterHelper.SetPageModePrintDirection(0);
//			HPRTPrinterHelper.SetAbsolutePrintPosition(288);
//			HPRTPrinterHelper.SetPageModeAbsoluteVerticalPosition(500);
//			InputStream open = getResources().getAssets().open("123.png");
//			Bitmap bitmap = BitmapFactory.decodeStream(open);
//			HPRTPrinterHelper.PrintBitmap(bitmap, (byte)0, (byte)0, 200);
			Print.PrintDataInPageMode();//打印
//			Print.CutPaper(1,8);

		}
		catch (Exception e)
		{
			Log.e("HPRTSDKSample", (new StringBuilder("Activity_Main --> onClickWIFI ")).append(e.getMessage()).toString());
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		try{
			Print.PortClose();
		}catch (Exception e){}
	}
}
