package com.android.zpl;

import static android.app.PendingIntent.FLAG_MUTABLE;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
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.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
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.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;


import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.luck.picture.lib.utils.ToastUtils;
import com.prt.common.config.FileType;
import com.prt.common.data.Phase;
import com.prt.common.data.PrinterStatus;
import com.prt.common.listener.PrintListener;
import com.prt.common.listener.PrinterStatusListener;
import com.prt.common.listener.SetResultListener;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import zpl.IPort;
import zpl.PublicFunction;
import zpl.ZPLPrinterHelper;
import rx.functions.Action1;
import zpl.listener.PrinterSNListener;


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 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.HPRTSDKSample";
    private PendingIntent mPermissionIntent = null;
    private static IPort Printer = null;
    private ZPLPrinterHelper zplPrinterHelper;
    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE"};

    private static final int REQUEST_ENABLE_BT = 2;
    private int taskID = 1000;

    @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);

            //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);
            Intent intent = new Intent(ACTION_USB_PERMISSION);
            intent.setPackage(thisCon.getPackageName());
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                mPermissionIntent = PendingIntent.getBroadcast(thisCon, 0, intent, FLAG_MUTABLE);
            } else {
                mPermissionIntent = PendingIntent.getBroadcast(thisCon, 0, intent, 0);
            }
            IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                thisCon.registerReceiver(mUsbReceiver, filter, RECEIVER_EXPORTED);
            } else {
                thisCon.registerReceiver(mUsbReceiver, filter);
            }

            PFun = new PublicFunction(thisCon);
            PAct = new PublicAction(thisCon);
            InitSetting();
            InitCombox();
            this.spnPrinterList.setOnItemSelectedListener(new OnItemSelectedPrinter());
            EnableBluetooth();
            zplPrinterHelper = ZPLPrinterHelper.getZPL(thisCon);
            initPrinterListener();
        } catch (Exception e) {
            Log.e("HPRTSDKSample", (new StringBuilder("Activity_Main --> onCreate ")).append(e.getMessage()).toString());
        }
    }

    private void initPrinterListener() {
        zplPrinterHelper.setPrintListener(phase -> {
            ToastUtils.showToast(thisCon, phase.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(R.string.sdk_type);
            if (strSDKType.equals("all"))
                arrPrinterList = ArrayAdapter.createFromResource(this, R.array.printer_list_zpl, android.R.layout.simple_spinner_item);
            if (strSDKType.equals("hprt"))
                arrPrinterList = ArrayAdapter.createFromResource(this, R.array.printer_list_hprt, 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();
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub
        }
    }

    //EnableBluetooth
    @SuppressLint("MissingPermission")
    private boolean EnableBluetooth() {
        boolean bRet = false;
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter != null) {
            if (mBluetoothAdapter.isEnabled())
                return true;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                RxPermissions rxPermissions = new RxPermissions(this);
                rxPermissions.request(Manifest.permission.BLUETOOTH_CONNECT).subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean aBoolean) {
                        if (aBoolean) {
                            if (ActivityCompat.checkSelfPermission(Activity_Main.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
                                return;
                            }
                        }
                    }
                });
            } else {
                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("SDKSample", (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 RESULT_CANCELED:
                    connectBT(data.getExtras().getString("SelectedBDAddress"));
                case ZPLPrinterHelper.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 RESULT_OK:
                    if (requestCode == PictureConfig.CHOOSE_REQUEST) {
//                        setPrintDialog(data);
                    }
                    return;
                case ZPLPrinterHelper.ACTIVITY_PRNFILE:
                    String strPRNFile = data.getExtras().getString("FilePath");
                    zplPrinterHelper.PrintBinaryFile(strPRNFile);
                    return;
            }
        } catch (Exception e) {
            Log.e("HPRTSDKSample", (new StringBuilder("Activity_Main --> onActivityResult ")).append(e.getMessage()).toString());
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void connectBT(String selectedBDAddress) {
        if (TextUtils.isEmpty(selectedBDAddress))
            return;
        final ProgressDialog progressDialog = new ProgressDialog(Activity_Main.this);
        progressDialog.setMessage(getString(R.string.activity_devicelist_connect));
        progressDialog.show();
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    final int result = zplPrinterHelper.PortOpen("Bluetooth," + selectedBDAddress);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (result == 0)
                                txtTips.setText(thisCon.getString(R.string.activity_main_connected));
                            else
                                txtTips.setText(thisCon.getString(R.string.activity_main_connecterr) + result);
                        }
                    });
                    progressDialog.dismiss();
                } catch (Exception e) {
                    progressDialog.dismiss();
                }
            }
        }.start();
    }

    @SuppressLint("NewApi")
    public void onClickConnect(View view) {
        if (!checkClick.isClickEvent()) return;

        try {
            if (zplPrinterHelper != null) {
                zplPrinterHelper.PortClose();
            }

            if (view.getId() == R.id.btnBT) {
                connectionBluetooth();
                return;
            } else if (view.getId() == R.id.btnWIFI) {
                ConnectType = "WiFi";
                Intent serverIntent = new Intent(thisCon, Activity_Wifi.class);
                serverIntent.putExtra("PN", PrinterName);
                startActivityForResult(serverIntent, ZPLPrinterHelper.ACTIVITY_CONNECT_WIFI);
                return;
            } else if (view.getId() == R.id.btnUSB) {
                ConnectType = "USB";
//				HPRTPrinter=new ZPLPrinterHelper(thisCon,arrPrinterList.getItem(spnPrinterList.getSelectedItemPosition()).toString());
                //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) {
                            HavePrinter = true;
                            mUsbManager.requestPermission(device, mPermissionIntent);
                        }
                    }
                }
                if (!HavePrinter)
                    txtTips.setText(thisCon.getString(R.string.activity_main_connect_usb_printer));
            }
        } catch (Exception e) {
            Log.e("HPRTSDKSample", (new StringBuilder("Activity_Main --> onClickConnect " + ConnectType)).append(e.getMessage()).toString());
        }
    }

    private void connectionBluetooth() {
        //获取蓝牙动态权限
        RxPermissions rxPermissions = new RxPermissions(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            rxPermissions.request(Manifest.permission.BLUETOOTH_ADMIN,
                    Manifest.permission.BLUETOOTH,
                    Manifest.permission.BLUETOOTH_CONNECT,
                    Manifest.permission.BLUETOOTH_SCAN,
                    Manifest.permission.ACCESS_FINE_LOCATION).subscribe(new Action1<Boolean>() {
                @Override
                public void call(Boolean aBoolean) {
                    if (aBoolean) {
                        ConnectType = "Bluetooth";
                        Intent intent = new Intent(thisCon, BTActivity.class);
                        intent.putExtra("TAG", 0);
                        startActivityForResult(intent, 0);
                    }
                }
            });
        } else {
            rxPermissions.request(Manifest.permission.BLUETOOTH_ADMIN,
                    Manifest.permission.BLUETOOTH,
                    Manifest.permission.ACCESS_FINE_LOCATION).subscribe(new Action1<Boolean>() {
                @Override
                public void call(Boolean aBoolean) {
                    if (aBoolean) {
                        ConnectType = "Bluetooth";
                        Intent intent = new Intent(thisCon, BTActivity.class);
                        intent.putExtra("TAG", 0);
                        startActivityForResult(intent, 0);
                    }
                }
            });
        }
    }

    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 (zplPrinterHelper.PortOpen(device) != 0) {
//				        		HPRTPrinter=null;
                                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) {
                        zplPrinterHelper.PortClose();
                    }
                }
            } catch (Exception e) {
                Log.e("HPRTSDKSample", (new StringBuilder("Activity_Main --> mUsbReceiver ")).append(e.getMessage()).toString());
            }
        }
    };


    public void onClickClose(View view) {
        if (!checkClick.isClickEvent()) return;

        try {
            if (zplPrinterHelper != null) {
                zplPrinterHelper.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 onClickDo(View view) {
        if (!checkClick.isClickEvent()) return;

        if (!ZPLPrinterHelper.IsOpened()) {
            Toast.makeText(thisCon, thisCon.getText(R.string.activity_main_tips), Toast.LENGTH_SHORT).show();
            return;
        } 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.btnTextFormat) {
            Intent myIntent = new Intent(this, Activity_TextFormat.class);
            startActivityFromChild(this, myIntent, 0);
        } else if (view.getId() == R.id.btnPrintImageFile) {
            printImageFile();
        } else if (view.getId() == R.id.btnPrintSN) {
            try {
                zplPrinterHelper.getPrinterSN(sn -> {
                            runOnUiThread(() -> {
                                Toast.makeText(thisCon, sn, Toast.LENGTH_SHORT).show();
                            });
                        }
                );
            } catch (Exception e) {
            }
        } 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.btnPrintTestPage) {
            try {
                zplPrinterHelper.selfTest();
            } catch (Exception e) {
                Log.e("HPRTSDKSample", (new StringBuilder("Activity_Main --> onClickWIFI ")).append(e.getMessage()).toString());
            }
//			upPrint();
        } else if (view.getId() == R.id.btnRFID) {
            try {
                zplPrinterHelper.start();
                zplPrinterHelper.writeRFID(2, 1, "中文".getBytes("GB2312"));
//                zplPrinterHelper.readRFID(2, 4, 1);
                zplPrinterHelper.end();
//                byte[] bytes = zplPrinterHelper.ReadData(3);
//                if (bytes != null && bytes.length > 0) {
//                    String hexStr = new String(bytes);
//                    byte[] hexByte = UtilityTooth.hexToByte(hexStr);
//                    Toast.makeText(thisCon, new String(hexByte, "GB2312"), Toast.LENGTH_SHORT).show();
//                }
            } catch (Exception e) {
            }
        } else if (view.getId() == R.id.btn_pdf) {
            printPDF();
        }
    }

    private void printImageFile() {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(Manifest.permission.READ_EXTERNAL_STORAGE).subscribe(new Action1<Boolean>() {
            @Override
            public void call(Boolean aBoolean) {
                if (aBoolean) {
                    PictureSelector.create(Activity_Main.this)
                            .openGallery(SelectMimeType.ofImage())
                            .setImageEngine(GlideEngine.createGlideEngine())
                            .setMaxSelectNum(1)
                            .forResult(new OnResultCallbackListener<LocalMedia>() {
                                @Override
                                public void onResult(ArrayList<LocalMedia> result) {
                                    setPrintDialog(result);
                                }

                                @Override
                                public void onCancel() {

                                }
                            });
                }
            }
        });
    }

    private void setPrintDialog(ArrayList<LocalMedia> result) {
        String path = result.get(0).getPath();
        Log.d("Print", "image path: " + path);
        if (path.contains("content://")) {
            Uri uri = Uri.parse(path);
            path = com.android.zpl.FileUtils.getFilePathByUri_BELOWAPI11(uri, this);
            Log.d("Print", "image path: " + path + "file:" + new File(path).exists());
        }
        final Bitmap bmp = BitmapFactory.decodeFile(path);
        if (bmp == null) {
            Toast.makeText(thisCon, "Image error", Toast.LENGTH_SHORT).show();
            return;
        }
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage(getString(R.string.activity_main_please_wait));
        progressDialog.show();
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    zplPrinterHelper.start();
                    zplPrinterHelper.setPrintHeight(bmp.getHeight());
                    zplPrinterHelper.printBitmap("0", "0", bmp);
                    zplPrinterHelper.end();
                    progressDialog.dismiss();
                    taskID++;
                } catch (Exception e) {
                    progressDialog.dismiss();
                }
            }
        }.start();
    }

    private void printPDF() {
        try {
            RxPermissions rxPermissions = new RxPermissions(this);
            rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE).subscribe(new Action1<Boolean>() {
                @Override
                public void call(Boolean aBoolean) {
                    if (aBoolean) {
                        try {
                            String fileName = getApplication().getFilesDir().getAbsolutePath() + "/Android_ZPL_SDK说明文档_V1.03.pdf";
                            File file = new File(fileName);
                            if (!file.exists()) {
                                InputStream inputStream = getResources().getAssets().open("Android_ZPL_SDK说明文档_V1.03.pdf");
                                UtilityTooth.writeFile(inputStream, file);
                            }
                            List<Bitmap> bitmaps = zplPrinterHelper.pdfToBitmap(thisCon, file, "1", 576);
                            if (bitmaps.size() > 0) {
                                zplPrinterHelper.start();
                                zplPrinterHelper.printBitmap("0", "0", 1, bitmaps.get(0));
                                zplPrinterHelper.end();
                            }
                        } catch (Exception e) {
                        }

                    }
                }
            });
        } catch (Exception e) {
        }
    }


    private void PrintSampleReceipt() {
        try {
            InputStream afis = this.getResources().getAssets().open("test2.prn");//打印模版放在assets文件夹里
            String path = new String(InputStreamToByte(afis), "utf-8");//打印模版以utf-8无bom格式保存
            zplPrinterHelper.printData(path);
        } catch (Exception e) {
            Log.e("HPRTSDKSample", (new StringBuilder("Activity_Main --> PrintSampleReceipt ")).append(e.getMessage()).toString());
        }
    }

    private byte[] InputStreamToByte(InputStream is) throws IOException {
        ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
        int ch;
        while ((ch = is.read()) != -1) {
            bytestream.write(ch);
        }
        byte imgdata[] = bytestream.toByteArray();
        bytestream.close();
        return imgdata;
    }


}
