package w.soulofpluto.posstock;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.epson.epos2.Epos2Exception;
import com.epson.epos2.discovery.DeviceInfo;
import com.epson.epos2.discovery.Discovery;
import com.epson.epos2.discovery.DiscoveryListener;
import com.epson.epos2.discovery.FilterOption;
import com.epson.epos2.printer.Printer;
import com.epson.epos2.printer.PrinterStatusInfo;
import com.epson.epos2.printer.ReceiveListener;
import com.squareup.okhttp.RequestBody;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import static w.soulofpluto.posstock.Constants.DeliveryslipAmt;
import static w.soulofpluto.posstock.Constants.DeliveryslipQty;
import static w.soulofpluto.posstock.Constants.JSON;

/*
 Create by Ramesh Babu
 */

public class CreateSaleBill extends AppCompatActivity implements View.OnClickListener,
        ReceiveListener, AdapterView.OnItemClickListener,DataInterface, TextView.OnEditorActionListener {
    private Button pluto_Print, send , generate_invoice;
    private Toolbar main_toolbar;
    private EditText cust_name, cust_number, ds_Number,last_four_digits;
    public Menu globalMenuItem;
    private TextView gross_amount,discount_amount,round_off,netamount;
    private PreferenceManager preferenceManager;
    private LinearLayout layout,data;
    private StringBuilder builder;
    private StringBuilder build;
    private String NetAmount;
    private ArrayList<Model> datalist;
    private JSONObject responseobj;
    private RecyclerView ds_list;
    ArrayList<String> arrayList;
    Dialog dialog;
    private static final int REQUEST_PERMISSION = 100;
    public static Printer mPrinter = null;
    private Context mContext = null;
    ListView bluetooth_list;
    private ArrayList<HashMap<String, String>> mPrinterList = null;
    private SimpleAdapter mPrinterListAdapter = null;
    private FilterOption mFilterOption = null;
    private TextView store_location;
    private Boolean initial = false;
    private String BankName;
    private int BankId;
    Dialog bankdialog;
    private DataPresenter dataPresenter;
    private Boolean print = false;
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_salebill);
        cust_name = findViewById(R.id.cust_name);
        cust_number = findViewById(R.id.cust_number);
        store_location = findViewById(R.id.store_location);
        ds_Number = findViewById(R.id.ds_Number);
        gross_amount = findViewById(R.id.gross_amount);
        discount_amount = findViewById(R.id.discount_amount);
        round_off = findViewById(R.id.round_off);
        netamount = findViewById(R.id.netamount);
        pluto_Print = findViewById(R.id.pluto_Print);
        send   = findViewById(R.id.send);
        layout = findViewById(R.id.layout);
        data   = findViewById(R.id.data);
        main_toolbar = findViewById(R.id.main_toolbar);
        ds_list = findViewById(R.id.ds_list);
        //last_four_digits = findViewById(R.id.last_four_digits);
        generate_invoice = findViewById(R.id.generate_invoice);
        //bank_details     = findViewById(R.id.bank_details);
        preferenceManager = new PreferenceManager(this);
        store_location.setText(preferenceManager.getStoreName());
        //pluto_pay.setOnClickListener(this);
        pluto_Print.setOnClickListener(this);
        generate_invoice.setOnClickListener(this);
        send.setOnClickListener(this);
        setSupportActionBar(main_toolbar);
        getSupportActionBar().setTitle(" Create Sale Bill ");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        builder = new StringBuilder();
        //build    = new StringBuilder();
        datalist = new ArrayList<>();
        requestRuntimePermission();
        mContext = this;
        dataPresenter = new DataPresenter(this,(DataInterface)this);
        ds_Number.setOnEditorActionListener(this);
        cust_number.addTextChangedListener(new AutoChecked());
    }

    class AutoChecked implements TextWatcher {
        public void afterTextChanged(Editable s){
            try{
                if(s.toString().length() == 10){
                    cust_name.requestFocus();
                    JSONObject object = new JSONObject();
                    try {
                        object.put("customer_phone",s.toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    RequestBody body = RequestBody.create(JSON,object.toString());
                    dataPresenter.CustomerName(Constants.BASE_URL+"/Customers/getCustomerByPhoneNumber",body);
                }
            }catch(NumberFormatException nfe){
                nfe.printStackTrace();
            }
        }
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
    }
    @Override
    protected void onResume(){
        super.onResume();
    }
    private void requestRuntimePermission() {
        if(Build.VERSION.SDK_INT < Build.VERSION_CODES.M){
            return;
        }
        int permissionStorage = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        int permissionLocation = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION);
        List<String> requestPermissions = new ArrayList<>();
        if(permissionStorage == PackageManager.PERMISSION_DENIED) {
            requestPermissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        if(permissionLocation == PackageManager.PERMISSION_DENIED) {
            requestPermissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        }
        if(!requestPermissions.isEmpty()) {
            ActivityCompat.requestPermissions(this, requestPermissions.toArray(new String[requestPermissions.size()]), REQUEST_PERMISSION);
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        if(requestCode != REQUEST_PERMISSION || grantResults.length == 0){
            return;
        }
        List<String> requestPermissions = new ArrayList<>();
        for(int i = 0; i < permissions.length; i++){
            if(permissions[i].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    && grantResults[i] == PackageManager.PERMISSION_DENIED){
                requestPermissions.add(permissions[i]);
            }
            if(permissions[i].equals(Manifest.permission.ACCESS_COARSE_LOCATION)
                    && grantResults[i] == PackageManager.PERMISSION_DENIED){
                requestPermissions.add(permissions[i]);
            }
        }
        if(!requestPermissions.isEmpty()){
            ActivityCompat.requestPermissions(this, requestPermissions.toArray(new String[requestPermissions.size()]), REQUEST_PERMISSION);
        }
    }
    private void DsData(final String Id) {
        arrayList = new ArrayList<>();
        build = new StringBuilder();
        if (datalist.size() > 0) {
            for (int i = 0; i < datalist.size(); i++) {
                Model data = datalist.get(i);
                if (data.getDelivery_slip_id().equalsIgnoreCase(Id)) {
                    datalist.remove(i);
                } else {
                    if (Id != "") {
                        if (build.toString().length() > 0) {
                            arrayList.add(data.getDelivery_slip_id());
                            build.append(Constants.PrintData(data.getDelivery_slip_id()));
                        } else {
                            arrayList.add(data.getDelivery_slip_id());
                            build.append(Constants.PrintData1(data.getDelivery_slip_id()));
                        }
                    }
                }
            }
            if (Id != "") {
                if (build.toString().length() > 0) {
                    build.append(Constants.PrintData(Id)).toString();
                } else {
                    build.append(Constants.PrintData1(Id)).toString();
                }
               Log.e("Array List Data ====>" , Id);
               Log.e("Array List Data1 ===>" , String.valueOf(arrayList));
            }
        } else {
            if (Id != "") {
                if (build.toString().length() > 0) {
                    build.append(Constants.PrintData(Id)).toString();
                } else {
                    build.append(Constants.PrintData1(Id)).toString();
                }
               Log.e("Array List Data ====>" , Id);
               Log.e("Array List Data1 ===>" , String.valueOf(arrayList));
                //Collections.sort(arrayList);
            } else {
                layout.setVisibility(View.GONE);
                Constants.getToast(this, "No data");
                //Constants.ProgressDialogDismiss();
            }
        }
        Log.e("Formation Data ===========>" , Constants.formdata(build.toString(), cust_name.getText().toString(), cust_number.getText().toString()));
        RequestBody body = RequestBody.create(JSON, Constants.formdata(build.toString(), cust_name.getText().toString(), cust_number.getText().toString()));
        if(Constants.isNetworkAvailable(this)) {
            dataPresenter.SendDeliverySlipNumber(Constants.BASE_URL + "/Sales/pre_sale_check", body,Id);
            Constants.ProgressDialogShow(CreateSaleBill.this);
        }else{
            Constants.getToast(CreateSaleBill.this,"Please check your internet connection");
        }
    }
    private void SetData(ArrayList<Model> dList){
        CreateSaleAdapter benifitsAdapter = new CreateSaleAdapter(CreateSaleBill.this, dList);
        ds_list.setLayoutManager(new LinearLayoutManager(this));
        ds_list.setAdapter(benifitsAdapter);
    }

    public void SetData(String Id){
        //System.out.println("Data =====>" + Id);
        //System.out.println("Before =====>" + datalist.size());
        for(int i = 0; i < datalist.size(); i++)

           Log.e("Before After =====>" , String.valueOf(datalist.size()));
        Remove();
    }

    private void Remove(){
        arrayList = new ArrayList<>();
        build = new StringBuilder();
        if (datalist.size() > 0){
            for(int i = 0; i < datalist.size(); i++){
                Model data = datalist.get(i);
                if (build.toString().length() > 0) {
                    build.append(Constants.PrintData(data.getDelivery_slip_id())).toString();
                } else {
                    build.append(Constants.PrintData1(data.getDelivery_slip_id())).toString();
                }
            }
            RequestBody body = RequestBody.create(JSON, Constants.formdata(build.toString(), cust_name.getText().toString(), cust_number.getText().toString()));
            if(Constants.isNetworkAvailable(CreateSaleBill.this)) {
                dataPresenter.SendDeliverySlipNumberremove(Constants.BASE_URL + "/Sales/pre_sale_check", body);
                Constants.ProgressDialogShow(CreateSaleBill.this);
            }else{
                Constants.getToast(CreateSaleBill.this,"Please check your internet connection");
            }
        } else {
            //Constants.ProgressDialogDismiss();
            layout.setVisibility(View.GONE);
            Constants.getToast(this, "No data");
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu){
        getMenuInflater().inflate(R.menu.menu_create, menu);
        globalMenuItem = menu;
        if(preferenceManager.getBLUETOOTH().length()>0){
            //System.out.println("connection ====>"+preferenceManager.getBLUETOOTH().length());
            globalMenuItem.findItem(R.id.dashboard_connection).setIcon(R.drawable.ic_bluetooth_indicator);
        }else{
            //System.out.println("connection1 ====>"+preferenceManager.getBLUETOOTH());
            globalMenuItem.findItem(R.id.dashboard_connection).setIcon(R.drawable.ic_bluetooth_signal_indicator);
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public void onBackPressed(){
        super.onBackPressed();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        switch(item.getItemId()){
            case android.R.id.home:
                 finish();
                break;
            case R.id.dashboard_logout:
                Logout(preferenceManager.getUserId());
                try {
                    Discovery.stop();
                    break;
                }catch (Epos2Exception e1){
                   Log.e("Output =====>",e1.getMessage());
                }
                break;
            case R.id.dashboard_connection:
                bluetoothpair();
                break;

            case R.id.dashboard_reload:
                startActivity(getIntent());
                finish();
                try {
                    Discovery.stop();
                    break;
                }catch (Epos2Exception e1){
                   //Log.e("Output =====>",e1.getMessage());
                }
                break;

        }
        return super.onOptionsItemSelected(item);
    }

    private void bluetoothpair(){
        dialog = new Dialog(this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.print_dialog);
        dialog.getWindow().setLayout(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);
        dialog.show();
        bluetooth_list              =  dialog.findViewById(R.id.bluetooth_list);
        ImageView refresh_bluetooth = dialog.findViewById(R.id.refresh_bluetooth);
        mPrinterList = new ArrayList<HashMap<String,String>>();
        mPrinterListAdapter = new SimpleAdapter(this, mPrinterList, R.layout.list_at,
                new String[] { "PrinterName", "Target" },
                new int[] { R.id.PrinterName, R.id.Target });
        bluetooth_list.setAdapter(mPrinterListAdapter);
        bluetooth_list.setOnItemClickListener(this);
        mFilterOption = new FilterOption();
        mFilterOption.setDeviceType(Discovery.TYPE_PRINTER);
        mFilterOption.setEpsonFilter(Discovery.FILTER_NAME);
        try{
            //Constants.ProgressDialogDismiss();
            //18072
            if(initial) {
                Discovery.stop();
                initial = false;
                Discovery.start(this, mFilterOption, mDiscoveryListener);
                Constants.ProgressDialogShow(this);
            }else{
                Discovery.start(this, mFilterOption, mDiscoveryListener);
                Constants.ProgressDialogShow(this);
            }
        }catch(Epos2Exception e){
            try {
                Discovery.start(this, mFilterOption, mDiscoveryListener);
                Constants.ProgressDialogShow(this);
            }catch (Epos2Exception e1){
                e1.getMessage();
            }
            if (e.getErrorStatus() != Epos2Exception.ERR_PROCESSING){
                ShowMsg.showException(e, "stop", mContext);

                return;
            }
        }finally {
        }
        refresh_bluetooth.setOnClickListener(v -> restartDiscovery());
    }
    private void restartDiscovery(){
        while (true) {
            try {
                //Constants.ProgressDialogDismiss();
                Discovery.stop();
                break;
            }
            catch (Epos2Exception e) {
                if (e.getErrorStatus() != Epos2Exception.ERR_PROCESSING) {
                    ShowMsg.showException(e, "stop", mContext);
                    return;
                }
            }
        }
        mPrinterList.clear();
        mPrinterListAdapter.notifyDataSetChanged();
        try {
            Discovery.start(this, mFilterOption, mDiscoveryListener);
            Constants.ProgressDialogShow(this);
        }
        catch (Exception e) {
            ShowMsg.showException(e, "stop", mContext);
        }
    }

    private DiscoveryListener mDiscoveryListener = deviceInfo -> runOnUiThread(new Runnable(){
        @Override
        public synchronized void run(){
            initial = true;
            HashMap<String, String> item = new HashMap<String, String>();
            item.put("PrinterName", deviceInfo.getDeviceName());
            item.put("Target", deviceInfo.getTarget());
            mPrinterList.add(item);
            mPrinterListAdapter.notifyDataSetChanged();
            Constants.ProgressDialogDismiss();
        }
    });

    private void Logout(String Id){
        if(Constants.isNetworkAvailable(CreateSaleBill.this)){
            dataPresenter.Logout(Constants.BASE_URL + "/login/doLogout/" + Id);
            Constants.ProgressDialogShow(CreateSaleBill.this);
        }else{
            Constants.getToast(CreateSaleBill.this,"Please check your internet connection");
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        try {
            Intent intent = new Intent();
            HashMap<String, String> item = mPrinterList.get(position);
            intent.putExtra(getString(R.string.title_target), item.get("Target"));
            dialog.dismiss();
            preferenceManager.setBLUETOOTH(item.get("Target"));
            invalidateOptionsMenu();
        }catch (NullPointerException np){
            np.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.pluto_Print:
                print = true;
                updateButtonState(false);
                if(!runPrintReceiptSequence()){
                    updateButtonState(true);
                }
                break;
            case R.id.generate_invoice:
                if(preferenceManager.getBLUETOOTH().length()>0) {
                    bankdialog = new Dialog(this);
                    bankdialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                    bankdialog.setCancelable(false);
                    bankdialog.setContentView(R.layout.dialog);
                    final Spinner bank_names = bankdialog.findViewById(R.id.bank_names);
                    last_four_digits = bankdialog.findViewById(R.id.last_four_digits);
                    last_four_digits.setOnEditorActionListener(this);
                    Button bank_submit = bankdialog.findViewById(R.id.bank_submit);
                    ImageView dialog_close = bankdialog.findViewById(R.id.dialog_close);

                    final ArrayList<String> arrayList = new ArrayList<>();
                    arrayList.add("Select Bank");
                    arrayList.add("Canara Bank");
                    arrayList.add("State Bank of India");
                    arrayList.add("Lakshmi Vilas Bank");

                    final ArrayList<Integer> arrayList1 = new ArrayList<>();
                    arrayList1.add(0);
                    arrayList1.add(6);
                    arrayList1.add(3);
                    arrayList1.add(4);

                    ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, arrayList);
                    bank_names.setAdapter(adapter);

                    bank_names.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                            BankName = arrayList.get(position);
                            BankId   = arrayList1.get(position);
                        }

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

                    dialog_close.setOnClickListener(v1 -> bankdialog.dismiss());
                    bank_submit.setOnClickListener(v12 -> {
                        if (BankName.equalsIgnoreCase("Select Bank") && last_four_digits.getText().toString().length() == 0) {
                            Constants.getToast(CreateSaleBill.this, "Please Select Bank and Enter last four digits");
                        } else if (BankName.equalsIgnoreCase("Select Bank")) {
                            Constants.getToast(CreateSaleBill.this, "Please Select Bank ");
                        } else if (last_four_digits.getText().toString().length() == 0) {
                            Constants.getToast(CreateSaleBill.this, "Enter last four digits");
                        } else if (last_four_digits.getText().toString().length() == 4) {
                            //dialog.dismiss();
                            if (Constants.isNetworkAvailable(CreateSaleBill.this)) {
                                Constants.hideSoftKeyBoardOnTabClicked(v12, CreateSaleBill.this);
                                PrintData(last_four_digits.getText().toString(), BankId);
                                //Constants.ProgreesDialogShow(CreateSaleBill.this);
                            }else{
                                Constants.getToast(CreateSaleBill.this,"Please check your internet connection");
                            }
                        }
                    });
                    bankdialog.show();
                }else{
                    Constants.getToast(this,"Please Pair Bluetooth Printer");
                }
                break;
            case R.id.send:
                if (TextUtils.isEmpty(ds_Number.getText().toString())) {
                    Constants.getToast(CreateSaleBill.this, "Enter Delivery Slip Id");
                } else {
                    if(preferenceManager.getBLUETOOTH().length()>0){
                        DsData(preferenceManager.getPrefix() + ds_Number.getText().toString());
                        Constants.hideKeyboard(this);
                    }else{
                        Constants.getToast(CreateSaleBill.this,"Please Connect Bluetooth Printer");
                    }
                }
                break;
        }
    }
    private boolean runPrintReceiptSequence(){
        if (!initializeObject()) {
           Log.e("runPrintReceipt","");
            return false;
        }
        if (!createReceiptData()) {
           Log.e("runPrintReceipt1","");
            finalizeObject();
            return false;
        }
        if (!printData()) {
            finalizeObject();
           Log.e("runPrintReceipt2","");
            return false;
        }
        return true;
    }

    private void finalizeObject(){
        if (mPrinter == null) {
            return;
        }
        mPrinter.clearCommandBuffer();
        mPrinter.setReceiveEventListener(null);
        mPrinter = null;
    }
    @Override
    public void onPtrReceive(final Printer printerObj, final int code, final PrinterStatusInfo status, final String printJobId) {
        runOnUiThread(new Runnable() {
            @Override
            public synchronized void run() {
                ShowMsg.showResult(code, makeErrorMessage(status), mContext);

                dispPrinterWarnings(status);

                updateButtonState(true);

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        disconnectPrinter();
                    }
                }).start();
            }
        });
    }


    private String makeErrorMessage(PrinterStatusInfo status){
        String msg = "";
        if (status.getOnline() == Printer.FALSE){
            msg += getString(R.string.handlingmsg_err_offline);
        }
        if (status.getConnection() == Printer.FALSE){
            msg += getString(R.string.handlingmsg_err_no_response);
        }
        if (status.getCoverOpen() == Printer.TRUE){
            msg += getString(R.string.handlingmsg_err_cover_open);
        }
        if (status.getPaper() == Printer.PAPER_EMPTY){
            msg += getString(R.string.handlingmsg_err_receipt_end);
        }
        if (status.getPaperFeed() == Printer.TRUE || status.getPanelSwitch() == Printer.SWITCH_ON){
            msg += getString(R.string.handlingmsg_err_paper_feed);
        }
        if (status.getErrorStatus() == Printer.MECHANICAL_ERR || status.getErrorStatus() == Printer.AUTOCUTTER_ERR){
            msg += getString(R.string.handlingmsg_err_autocutter);
            msg += getString(R.string.handlingmsg_err_need_recover);
        }
        if (status.getErrorStatus() == Printer.UNRECOVER_ERR){
            msg += getString(R.string.handlingmsg_err_unrecover);
        }
        if (status.getErrorStatus() == Printer.AUTORECOVER_ERR){
            if (status.getAutoRecoverError() == Printer.HEAD_OVERHEAT) {
                msg += getString(R.string.handlingmsg_err_overheat);
                msg += getString(R.string.handlingmsg_err_head);
            }
            if (status.getAutoRecoverError() == Printer.MOTOR_OVERHEAT){
                msg += getString(R.string.handlingmsg_err_overheat);
                msg += getString(R.string.handlingmsg_err_motor);
            }
            if (status.getAutoRecoverError() == Printer.BATTERY_OVERHEAT){
                msg += getString(R.string.handlingmsg_err_overheat);
                msg += getString(R.string.handlingmsg_err_battery);
            }
            if (status.getAutoRecoverError() == Printer.WRONG_PAPER){
                msg += getString(R.string.handlingmsg_err_wrong_paper);
            }
        }
        if (status.getBatteryLevel() == Printer.BATTERY_LEVEL_0){
            msg += getString(R.string.handlingmsg_err_battery_real_end);
        }
        return msg;
    }
    private boolean printData(){
        if(mPrinter == null){
            return false;
        }
        if (!connectPrinter()) {
            return false;
        }

        PrinterStatusInfo status = mPrinter.getStatus();

        dispPrinterWarnings(status);

        if (!isPrintable(status)) {
            ShowMsg.showMsg(makeErrorMessage(status), mContext);
            try {
                mPrinter.disconnect();
            }
            catch (Exception ex) {
                // Do nothing
            }
            return false;
        }

        try {
            mPrinter.sendData(Printer.PARAM_DEFAULT);
        }
        catch (Exception e) {
            ShowMsg.showException(e, "sendData", mContext);
            try {
                mPrinter.disconnect();
            }
            catch (Exception ex) {
                // Do nothing
            }
            return false;
        }

        return true;
    }

    private void dispPrinterWarnings(PrinterStatusInfo status) {
        //EditText edtWarnings = (EditText)findViewById(R.id.edtWarnings);
        String warningsMsg = "";
        if (status == null) {
            return;
        }
        if (status.getPaper() == Printer.PAPER_NEAR_END) {
            warningsMsg += getString(R.string.handlingmsg_warn_receipt_near_end);

        }
        if (status.getPaper() == Printer.PAPER_EMPTY) {
            warningsMsg += "Paper Roll Is Empty";

        }
        if (status.getBatteryLevel() == Printer.BATTERY_LEVEL_1) {
            warningsMsg += getString(R.string.handlingmsg_warn_battery_near_end);
        }
        if(warningsMsg.length()>0){
            Constants.getToast(CreateSaleBill.this,warningsMsg);
        }
       Log.e("Print ======>", String.valueOf(status.getPaper()));
        // edtWarnings.setText(warningsMsg);
    }
    private boolean isPrintable(PrinterStatusInfo status) {
        if (status == null) {
            return false;
        }

        if (status.getConnection() == Printer.FALSE) {
            return false;
        }
        else if (status.getOnline() == Printer.FALSE) {
            return false;
        }
        else {

        }

        return true;
    }

    private void disconnectPrinter() {
        if (mPrinter == null) {
            return;
        }
        try {
            mPrinter.endTransaction();
        }
        catch (final Exception e) {

        }
        try {
            mPrinter.disconnect();
        }
        catch (final Exception e) {
        }
        finalizeObject();
    }
    private boolean connectPrinter() {
        boolean isBeginTransaction = false;
        if (mPrinter == null) {
            return false;
        }
        try {
            //System.out.println("Checking Printer ======>"+com.epson.epos2.printer.Printer.PARAM_DEFAULT);
            mPrinter.connect(preferenceManager.getBLUETOOTH(), 30000);
           //Log.e("Shared Preferences Bluetooth ========>",preferenceManager.getBLUETOOTH());
        }
        catch (Exception e) {
            ShowMsg.showException(e, "connect", mContext);
            return false;
        }
        try {
            mPrinter.beginTransaction();
            isBeginTransaction = true;
        }
        catch (Exception e) {
            ShowMsg.showException(e, "beginTransaction", mContext);
        }
        if (isBeginTransaction == false) {
            try {
                mPrinter.disconnect();
            }
            catch (Epos2Exception e) {
                // Do nothing
                return false;
            }
        }
        return true;
    }
    private boolean initializeObject(){
        try{
            mPrinter = new Printer(1,6,mContext);
        }
        catch (Exception e) {
            ShowMsg.showException(e, "Printer", mContext);
            Constants.ProgressDialogDismiss();
            return false;
        }
        mPrinter.setReceiveEventListener(this);
        return true;
    }
    private void updateButtonState(boolean state) {
        pluto_Print.setEnabled(state);
       Log.e("Data State Enables===>", String.valueOf(state));
    }
    private boolean createReceiptData(){
        String method = "";
        StringBuilder textData = new StringBuilder();
        Constants.ProgressDialogDismiss();
        if(print){
            print = false;
            try {
                if (mPrinter == null) {
                    return false;
                }
                if (responseobj.has("data")) {
                   Log.e("Response Data =============>" ,  String.valueOf(responseobj));
                    JSONObject dataobj = responseobj.getJSONObject("data");
                    JSONObject dataobject = dataobj.getJSONObject("invoice_data");

                    if (dataobject.has("website")) {
                        if (dataobject.getString("website").equalsIgnoreCase("www.kanchivml.com")) {
                            try {
                                Bitmap vml = BitmapFactory.decodeResource(getResources(), R.drawable.vara);
                                method = "addTextAlign";
                                mPrinter.addTextAlign(Printer.ALIGN_CENTER);

                                method = "addImage";
                                mPrinter.addImage(vml, 0, 0,
                                        vml.getWidth(),
                                        vml.getHeight(),
                                        Printer.COLOR_1,
                                        Printer.MODE_MONO,
                                        Printer.HALFTONE_DITHER,
                                        Printer.PARAM_DEFAULT,
                                        Printer.COMPRESS_AUTO);

                                method = "addFeedLine";
                                mPrinter.addFeedLine(1);
                            } catch (Epos2Exception eps) {
                                eps.getMessage();
                            }
                        } else if (dataobject.getString("website").equalsIgnoreCase("www.themandir.com")) {
                            try {
                                Bitmap vml = BitmapFactory.decodeResource(getResources(), R.drawable.mandir);
                                method = "addTextAlign";
                                mPrinter.addTextAlign(Printer.ALIGN_CENTER);

                                method = "addImage";
                                mPrinter.addImage(vml, 0, 0,
                                        vml.getWidth(),
                                        vml.getHeight(),
                                        Printer.COLOR_1,
                                        Printer.MODE_MONO,
                                        Printer.HALFTONE_DITHER,
                                        Printer.PARAM_DEFAULT,
                                        Printer.COMPRESS_AUTO);

                                method = "addFeedLine";
                                mPrinter.addFeedLine(1);
                            } catch (Epos2Exception eps) {
                                eps.getMessage();
                            }
                        } else if (dataobject.getString("website").equalsIgnoreCase("www.klmfashionmall.com")) {
                            try {
                                Bitmap vml = BitmapFactory.decodeResource(getResources(), R.drawable.klm);
                                method = "addTextAlign";
                                mPrinter.addTextAlign(Printer.ALIGN_CENTER);

                                method = "addImage";
                                mPrinter.addImage(vml, 0, 0,
                                        vml.getWidth(),
                                        vml.getHeight(),
                                        Printer.COLOR_1,
                                        Printer.MODE_MONO,
                                        Printer.HALFTONE_DITHER,
                                        Printer.PARAM_DEFAULT,
                                        Printer.COMPRESS_AUTO);

                                method = "addFeedLine";
                                mPrinter.addFeedLine(1);
                            } catch (Epos2Exception eps) {
                                eps.getMessage();
                            }
                        } else if (dataobject.getString("website").equalsIgnoreCase("www.kalamandir.com")) {
                            try {
                                Bitmap vml = BitmapFactory.decodeResource(getResources(), R.drawable.kala);
                                method = "addTextAlign";
                                mPrinter.addTextAlign(Printer.ALIGN_CENTER);

                                method = "addImage";

                                mPrinter.addImage(vml, 0, 0,
                                        vml.getWidth(),
                                        vml.getHeight(),
                                        Printer.COLOR_1,
                                        Printer.MODE_MONO,
                                        Printer.HALFTONE_DITHER,
                                        Printer.PARAM_DEFAULT,
                                        Printer.COMPRESS_AUTO);

                                method = "addFeedLine";
                                mPrinter.addFeedLine(1);
                            } catch (Epos2Exception eps) {
                                eps.getMessage();
                            }
                        }
                    }
                    if (dataobject.has("company_name")) {
                        method = "addTextAlign";
                        mPrinter.addTextAlign(Printer.ALIGN_CENTER);
                        mPrinter.addFeedLine(1);
                        textData.append(dataobject.getString("company_name") + "\n");
                        method = "addText";
                        mPrinter.addText(textData.toString());
                        textData.delete(0, textData.length());

                    }
                    if (dataobject.has("store_name")) {
                        method = "addTextAlign";
                        mPrinter.addTextAlign(Printer.ALIGN_CENTER);
                        textData.append(dataobject.getString("store_name") + "\n");
                        method = "addText";
                        mPrinter.addText(textData.toString());
                        textData.delete(0, textData.length());
                    }
                    if (dataobject.has("addr2")) {
                        method = "addTextAlign";
                        mPrinter.addTextAlign(Printer.ALIGN_CENTER);
                        textData.append(dataobject.getString("addr1") + "\n" + dataobject.getString("addr2") + "\n");
                       Log.e("Data ======>" , dataobject.getString("addr3"));
                        if (dataobject.getString("addr3").equalsIgnoreCase("null")) {
                        } else {
                            textData.append(dataobject.getString("addr3") + "\n");
                        }
                        method = "addText";
                        mPrinter.addText(textData.toString());
                        textData.delete(0, textData.length());
                    }
                    if (dataobject.has("showroom_phone_no")) {
                        method = "addTextAlign";
                        mPrinter.addTextAlign(Printer.ALIGN_CENTER);
                        textData.append(dataobject.getString("showroom_phone_no") + "\n \n");
                        method = "addText";
                        mPrinter.addText(textData.toString());
                        textData.delete(0, textData.length());
                    }
                    if (dataobject.has("website")) {
                        method = "addTextAlign";
                        mPrinter.addTextAlign(Printer.ALIGN_CENTER);
                        textData.append(dataobject.getString("website") + "\n");
                        method = "addText";
                        mPrinter.addText(textData.toString());
                        textData.delete(0, textData.length());
                    }
                    if (dataobject.has("gstno")) {
                        method = "addTextAlign";
                        mPrinter.addTextAlign(Printer.ALIGN_CENTER);
                        textData.append("GSTIN : " + dataobject.getString("gstno") + "\n\n");
                        textData.append("\n");
                        textData.append("Retail Invoice \n");
                        method = "addText";
                        mPrinter.addText(textData.toString());
                        textData.delete(0, textData.length());


                        method = "addTextAlign";
                        mPrinter.addTextAlign(Printer.ALIGN_LEFT);
                        textData.append(Constants.dashed);
                        textData.append(" Memo No  : " + dataobject.getString("memono") + "\n");
                        textData.append(" Date     : " + dataobject.getString("BillDate") + "\n");
                       Log.e("name ===================>" , dataobject.getString("customer"));
                        if (dataobject.getString("customer") != "NA")
                            textData.append(" Customer : " + dataobject.getString("customer") + "\n");
                       Log.e("name ===================>" , dataobject.getString("mobile"));
                        if (dataobject.getString("mobile") != "NA")
                            textData.append(" Ph No    : " + dataobject.getString("mobile") + "\n");
                        textData.append(Constants.dashed);

                        method = "addText";
                        mPrinter.addText(textData.toString());
                        textData.delete(0, textData.length());
                    }
                    if (dataobject.has("memono")) {
                    }
                    if (dataobject.has("BillDate")) {
                    }
                    if (dataobject.has("customer")) {

                    }
                    if (dataobject.has("mobile")) {

                    }
                    if (dataobject.has("bill_lines")) {
                        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                            method = "addTextAlign";
                            mPrinter.addTextAlign(Printer.ALIGN_LEFT);
                            textData.append(" SL Barcode    Qty MRP       Disc     Amount    " + "\n");
                            mPrinter.addText(textData.toString());
                            textData.delete(0, textData.length());

                            method = "addTextAlign";
                            mPrinter.addTextAlign(Printer.ALIGN_LEFT);
                            textData.append(Constants.dashed);
                            mPrinter.addText(textData.toString());
                            textData.delete(0, textData.length());
                            JSONObject da = dataobject.getJSONObject("bill_lines");
                            Iterator<String> keys = da.keys();
                            while (keys.hasNext()) {
                                String key = keys.next();
                                if (da.get(key) instanceof JSONArray) {
                                    // do something with jsonObject here
                                   Log.e("Connection  =====>" , String.valueOf(da));
                                   Log.e("Connection  =====>" , key);
                                    JSONArray bill_data = new JSONArray(da.getString(key));
                                    for (int i = 0; i < bill_data.length(); i++) {
                                        JSONObject bill_object = bill_data.getJSONObject(i);
                                        method = "addTextAlign";
                                        mPrinter.addTextAlign(Printer.ALIGN_LEFT);
                                        textData.append(" " + Constants.SL(bill_object.getString("sno")) +
                                                Constants.Barcode(bill_object.getString("barcode"))
                                                + Constants.Qty(bill_object.getString("qty")) + Constants.Mrp(bill_object.getString("item_rsp"))
                                                + Constants.Dis(bill_object.getString("item_qty_disc"))
                                                + Constants.Total(bill_object.getString("item_qty_payable_amount")));
                                        mPrinter.addText(textData.toString());
                                        textData.delete(0, textData.length());
                                        method = "addTextAlign";
                                        mPrinter.addTextAlign(Printer.ALIGN_LEFT);
                                        textData.append("   HSN " + bill_object.getString("hsn") + "  " + "Gst %" + bill_object.getString("gst_per") + " "
                                                + " Gst Amt   " + bill_object.getString("gst_amount") + "\n");
                                        mPrinter.addText(textData.toString());
                                        textData.delete(0, textData.length());

                                        mPrinter.addTextAlign(Printer.ALIGN_LEFT);
                                        textData.append("    SM " + bill_object.getString("sm") + "         " + bill_object.getString("perticulars") + "\n");

                                        textData.append(Constants.dashed);
                                        mPrinter.addText(textData.toString());
                                        textData.delete(0, textData.length());
                                    }
                                }
                            }
                        }
                    }
                    method = "addText";
                    mPrinter.addTextAlign(Printer.ALIGN_LEFT);
                    textData.append(" Gross Amount  : " + Constants.Gross(dataobject.getString("total_mrp")) + "\n");
                    textData.append(" Total Savings : " + Constants.TotalSavings(dataobject.getString("total_saving")) + "\n\n");
                    method = "addText";
                    mPrinter.addText(textData.toString());
                    textData.delete(0, textData.length());
                    method = "addText";
                    mPrinter.addTextAlign(Printer.ALIGN_CENTER);
                    method = "addTextSize";
                    mPrinter.addTextSize(2, 1);
                    method = "addText";
                    mPrinter.addText("Total Qty   :   " + dataobject.getString("total_qty") + "\n");
                    mPrinter.addText("Net Amount  :   " + dataobject.getString("total_payable") + "\n");
                    mPrinter.addText(textData.toString());
                    textData.delete(0, textData.length());
                    method = "addTextSize";

                    mPrinter.addTextSize(1, 1);
                    method = "addFeedLine";
                    mPrinter.addFeedLine(1);


                    method = "addText";
                    mPrinter.addText(textData.toString());
                    textData.delete(0, textData.length());

                    mPrinter.addTextAlign(Printer.ALIGN_LEFT);
                    textData.append(Constants.dashed);
                    mPrinter.addText(textData.toString());
                    textData.delete(0, textData.length());

                    if (dataobject.has("mop")) {
                        JSONArray mop = dataobject.getJSONArray("mop");
                       Log.e("Mop =====>" , String.valueOf(mop));
                        textData.delete(0, textData.length());
                        for (int L = 0; L < mop.length(); L++) {
                            JSONObject object = mop.getJSONObject(L);
                            method = "addTextAlign";
                            mPrinter.addTextAlign(Printer.ALIGN_LEFT);
                            method = "addText";
                            mPrinter.addText(" " + Constants.RecievedCashText(object.getString("paidtype")) + Constants.RecievedCash(object.getString("paidamount")) + "\n");
                        }
                    }


                    method = "addText";
                    mPrinter.addTextAlign(Printer.ALIGN_CENTER);
                    textData.append("\n" + "  Tax Details " + "\n");

                    method = "addText";
                    mPrinter.addText(textData.toString());
                    textData.delete(0, textData.length());
                    method = "addTextAlign";

                    mPrinter.addTextAlign(Printer.ALIGN_LEFT);
                    textData.append(Constants.dashed);
                    mPrinter.addText(textData.toString());
                    textData.delete(0, textData.length());

                    method = "addText";
                    mPrinter.addTextAlign(Printer.ALIGN_LEFT);
                    textData.append(" GST%   Taxable      CGST     SGST     IGST     " + "\n");
                    mPrinter.addText(textData.toString());
                    textData.delete(0, textData.length());

                    if (dataobject.has("gst_lines")) {
                        JSONArray TaxArray = new JSONArray(dataobject.getString("gst_lines"));
                        for (int j = 0; j < TaxArray.length(); j++) {
                            JSONObject taxoObject = TaxArray.getJSONObject(j);
                            JSONObject taxdata = new JSONObject();

                            method = "addText";
                            mPrinter.addTextAlign(Printer.ALIGN_LEFT);
                            textData.append(" " + Constants.GST(taxoObject.getString("gst_per").trim()) + Constants.Taxable(taxoObject.getString("taxable"))
                                    + Constants.CGST(taxoObject.getString("cgst")) + Constants.CGST(taxoObject.getString("sgst"))
                                    + Constants.CGST(taxoObject.getString("igst")) + "\n");
                            mPrinter.addText(textData.toString());
                            textData.delete(0, textData.length());
                        }
                        if (dataobject.has("gst_total")) {
                            JSONObject jsonObject = new JSONObject(dataobject.getString("gst_total"));
                            method = "addText";
                            textData.append(" Total  " + Constants.Taxable(jsonObject.getString("t_taxable")) + Constants.CGST(jsonObject.getString("t_cgst"))
                                    + Constants.CGST(jsonObject.getString("t_sgst")) + Constants.CGST(jsonObject.getString("t_igst")) + "\n");
                            mPrinter.addText(textData.toString());
                            textData.delete(0, textData.length());
                        }
                    }

                    method = "addText";
                    textData.append(Constants.dashed);
                    mPrinter.addText(textData.toString());
                    textData.delete(0, textData.length());

                    method = "addText";
                    mPrinter.addTextAlign(Printer.ALIGN_LEFT);
                    textData.append(" Biller : " + dataobject.getString("biller") + "\n");
                    mPrinter.addText(textData.toString());
                    textData.delete(0, textData.length());

                    method = "addText";
                    mPrinter.addTextAlign(Printer.ALIGN_CENTER);
                    textData.append("\n Delivery Slip Summary\n\n");
                    mPrinter.addText(textData.toString());
                    textData.delete(0, textData.length());

                    if (dataobject.has("ds_numbers")) {
                        JSONArray dslipArray = dataobject.getJSONArray("ds_numbers");
                       Log.e("DS NUMBERS =====>" , String.valueOf(dslipArray));
                        method = "addText";
                        mPrinter.addTextAlign(Printer.ALIGN_LEFT);
                        textData.append(" DS Number           Qty          Amount        ");
                        mPrinter.addText(textData.toString());
                        textData.delete(0, textData.length());
                        for (int m = 0; m < dslipArray.length(); m++) {
                            JSONObject object = dslipArray.getJSONObject(m);
                            method = "addTextAlign";
                            mPrinter.addTextAlign(Printer.ALIGN_LEFT);
                            method = "addText";
                            mPrinter.addText(" " + Constants.Deliveryslipnumber(object.getString("ds_no")) + DeliveryslipQty(object.getString("qty")) + DeliveryslipAmt(object.getString("ds_amount")));
                            textData.delete(0, textData.length());
                        }
                    }

                    method = "addText";
                    textData.append("\n" + Constants.dashed);
                    mPrinter.addText(textData.toString());
                    textData.delete(0, textData.length());


                    method = "addTextSize";
                    mPrinter.addTextSize(2, 2);
                    method = "addText";
                    mPrinter.addTextAlign(Printer.ALIGN_CENTER);
                    mPrinter.addText(dataobject.getString("memono") + "\n\n");

                    method = "addTextSize";

                    mPrinter.addTextSize(1, 1);

                    Bitmap logoData1 = BitmapFactory.decodeResource(getResources(), R.drawable.cash_paid);
                    final int barcodeWidth = 2;
                    final int barcodeHeight = 100;

                    if (mPrinter == null) {
                        return false;
                    }

                    try {
                        method = "addTextAlign";
                        mPrinter.addTextAlign(Printer.ALIGN_CENTER);

                        method = "addImage";
                        mPrinter.addImage(logoData1, 0, 0,
                                logoData1.getWidth(),
                                logoData1.getHeight(),
                                Printer.COLOR_1,
                                Printer.MODE_MONO,
                                Printer.HALFTONE_DITHER,
                                Printer.PARAM_DEFAULT,
                                Printer.COMPRESS_AUTO);

                        method = "addFeedLine";
                        mPrinter.addFeedLine(1);
                    } catch (Epos2Exception eps) {
                        eps.getMessage();
                    }


                    if (dataobject.has("ds_number_last_numbers")) {
                        JSONArray dsArray = dataobject.getJSONArray("ds_number_last_numbers");
                       Log.e("DS NUMBERS =====>" , String.valueOf(dsArray));

                        for (int n = 0; n < dsArray.length(); n++) {
                            method = "addText";
                            mPrinter.addTextAlign(Printer.ALIGN_CENTER);

                            method = "addTextSize";
                            mPrinter.addTextSize(5, 5);
                            method = "addText";
                            mPrinter.addText("\n" + dsArray.get(n) + "\n");
                        }
                    }

                    method = "addCut";
                    mPrinter.addCut(Printer.CUT_FEED);

                    textData.delete(0, textData.length());
                    method = "addTextSize";

                    mPrinter.addTextSize(1, 1);
                    method = "addFeedLine";
                    mPrinter.addFeedLine(1);

                }

            } catch (JSONException jo) {
                jo.printStackTrace();
            } catch (Epos2Exception e) {
                e.printStackTrace();
            } catch (Exception e) {
               Log.e("Error Message ======>" , e.getMessage());
                ShowMsg.showException(e, method, mContext);
                return false;
            }
        }else {
            for (int k = 0; k < 2; k++) {
                try {
                    if (mPrinter == null) {
                        return false;
                    }
                    if (responseobj.has("data")) {
                       Log.e("Response Data =============>" , String.valueOf(responseobj));
                        JSONObject dataobj = responseobj.getJSONObject("data");
                        JSONObject dataobject = dataobj.getJSONObject("invoice_data");

                        if (dataobject.has("website")) {
                            if (dataobject.getString("website").equalsIgnoreCase("www.kanchivml.com")) {
                                try {
                                    Bitmap vml = BitmapFactory.decodeResource(getResources(), R.drawable.vara);
                                    method = "addTextAlign";
                                    mPrinter.addTextAlign(Printer.ALIGN_CENTER);

                                    method = "addImage";
                                    mPrinter.addImage(vml, 0, 0,
                                            vml.getWidth(),
                                            vml.getHeight(),
                                            Printer.COLOR_1,
                                            Printer.MODE_MONO,
                                            Printer.HALFTONE_DITHER,
                                            Printer.PARAM_DEFAULT,
                                            Printer.COMPRESS_AUTO);

                                    method = "addFeedLine";
                                    mPrinter.addFeedLine(1);
                                } catch (Epos2Exception eps) {
                                    eps.getMessage();
                                }
                            } else if (dataobject.getString("website").equalsIgnoreCase("www.themandir.com")) {
                                try {
                                    Bitmap vml = BitmapFactory.decodeResource(getResources(), R.drawable.mandir);
                                    method = "addTextAlign";
                                    mPrinter.addTextAlign(Printer.ALIGN_CENTER);

                                    method = "addImage";
                                    mPrinter.addImage(vml, 0, 0,
                                            vml.getWidth(),
                                            vml.getHeight(),
                                            Printer.COLOR_1,
                                            Printer.MODE_MONO,
                                            Printer.HALFTONE_DITHER,
                                            Printer.PARAM_DEFAULT,
                                            Printer.COMPRESS_AUTO);

                                    method = "addFeedLine";
                                    mPrinter.addFeedLine(1);
                                } catch (Epos2Exception eps) {
                                    eps.getMessage();
                                }
                            } else if (dataobject.getString("website").equalsIgnoreCase("www.klmfashionmall.com")) {
                                try {
                                    Bitmap vml = BitmapFactory.decodeResource(getResources(), R.drawable.klm);
                                    method = "addTextAlign";
                                    mPrinter.addTextAlign(Printer.ALIGN_CENTER);

                                    method = "addImage";
                                    mPrinter.addImage(vml, 0, 0,
                                            vml.getWidth(),
                                            vml.getHeight(),
                                            Printer.COLOR_1,
                                            Printer.MODE_MONO,
                                            Printer.HALFTONE_DITHER,
                                            Printer.PARAM_DEFAULT,
                                            Printer.COMPRESS_AUTO);

                                    method = "addFeedLine";
                                    mPrinter.addFeedLine(1);
                                } catch (Epos2Exception eps) {
                                    eps.getMessage();
                                }
                            } else if (dataobject.getString("website").equalsIgnoreCase("www.kalamandir.com")) {
                                try {
                                    Bitmap vml = BitmapFactory.decodeResource(getResources(), R.drawable.kala);
                                    method = "addTextAlign";
                                    mPrinter.addTextAlign(Printer.ALIGN_CENTER);

                                    method = "addImage";

                                    mPrinter.addImage(vml, 0, 0,
                                            vml.getWidth(),
                                            vml.getHeight(),
                                            Printer.COLOR_1,
                                            Printer.MODE_MONO,
                                            Printer.HALFTONE_DITHER,
                                            Printer.PARAM_DEFAULT,
                                            Printer.COMPRESS_AUTO);

                                    method = "addFeedLine";
                                    mPrinter.addFeedLine(1);
                                } catch (Epos2Exception eps) {
                                    eps.getMessage();
                                }
                            }
                        }

                        if (dataobject.has("company_name")) {
                            method = "addTextAlign";
                            mPrinter.addTextAlign(Printer.ALIGN_CENTER);
                            mPrinter.addFeedLine(1);
                            textData.append(dataobject.getString("company_name") + "\n");
                            method = "addText";
                            mPrinter.addText(textData.toString());
                            textData.delete(0, textData.length());

                        }
                        if (dataobject.has("store_name")) {
                            method = "addTextAlign";
                            mPrinter.addTextAlign(Printer.ALIGN_CENTER);
                            textData.append(dataobject.getString("store_name") + "\n");
                            method = "addText";
                            mPrinter.addText(textData.toString());
                            textData.delete(0, textData.length());
                        }
                        if (dataobject.has("addr2")) {
                            method = "addTextAlign";
                            mPrinter.addTextAlign(Printer.ALIGN_CENTER);
                            textData.append(dataobject.getString("addr1") + "\n" + dataobject.getString("addr2") + "\n");
                           Log.e("Data ======>" , dataobject.getString("addr3"));
                            if (dataobject.getString("addr3").equalsIgnoreCase("null")) {
                            } else {
                                textData.append(dataobject.getString("addr3") + "\n");
                            }
                            method = "addText";
                            mPrinter.addText(textData.toString());
                            textData.delete(0, textData.length());
                        }
                        if (dataobject.has("showroom_phone_no")) {
                            method = "addTextAlign";
                            mPrinter.addTextAlign(Printer.ALIGN_CENTER);
                            textData.append(dataobject.getString("showroom_phone_no") + "\n \n");
                            method = "addText";
                            mPrinter.addText(textData.toString());
                            textData.delete(0, textData.length());
                        }
                        if (dataobject.has("website")) {
                            method = "addTextAlign";
                            mPrinter.addTextAlign(Printer.ALIGN_CENTER);
                            textData.append(dataobject.getString("website") + "\n");
                            method = "addText";
                            mPrinter.addText(textData.toString());
                            textData.delete(0, textData.length());
                        }
                        if (dataobject.has("gstno")) {
                            method = "addTextAlign";
                            mPrinter.addTextAlign(Printer.ALIGN_CENTER);
                            textData.append("GSTIN : " + dataobject.getString("gstno") + "\n\n");
                            textData.append("\n");
                            textData.append("Retail Invoice \n");
                            method = "addText";
                            mPrinter.addText(textData.toString());
                            textData.delete(0, textData.length());


                            method = "addTextAlign";
                            mPrinter.addTextAlign(Printer.ALIGN_LEFT);
                            textData.append(Constants.dashed);
                            textData.append(" Memo No  : " + dataobject.getString("memono") + "\n");
                            textData.append(" Date     : " + dataobject.getString("BillDate") + "\n");
                           Log.e("name ===================>" , dataobject.getString("customer"));
                            if (dataobject.getString("customer") != "NA")
                                textData.append(" Customer : " + dataobject.getString("customer") + "\n");
                           Log.e("name ===================>" , dataobject.getString("mobile"));
                            if (dataobject.getString("mobile") != "NA")
                                textData.append(" Ph No    : " + dataobject.getString("mobile") + "\n");
                            textData.append(Constants.dashed);

                            method = "addText";
                            mPrinter.addText(textData.toString());
                            textData.delete(0, textData.length());
                        }
                        if (dataobject.has("memono")) {
                        }
                        if (dataobject.has("BillDate")) {
                        }
                        if (dataobject.has("customer")) {

                        }
                        if (dataobject.has("mobile")) {

                        }
                        if (dataobject.has("bill_lines")) {
                            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                                method = "addTextAlign";
                                mPrinter.addTextAlign(Printer.ALIGN_LEFT);
                                textData.append(" SL Barcode    Qty MRP       Disc     Amount    " + "\n");
                                mPrinter.addText(textData.toString());
                                textData.delete(0, textData.length());

                                method = "addTextAlign";
                                mPrinter.addTextAlign(Printer.ALIGN_LEFT);
                                textData.append(Constants.dashed);
                                mPrinter.addText(textData.toString());
                                textData.delete(0, textData.length());
                                JSONObject da = dataobject.getJSONObject("bill_lines");
                                Iterator<String> keys = da.keys();
                                while (keys.hasNext()) {
                                    String key = keys.next();
                                    if (da.get(key) instanceof JSONArray) {
                                        // do something with jsonObject here
                                       Log.e("Connection  =====>" , String.valueOf(da));
                                       Log.e("Connection  =====>" , key);
                                        JSONArray bill_data = new JSONArray(da.getString(key));
                                        for (int i = 0; i < bill_data.length(); i++) {
                                            JSONObject bill_object = bill_data.getJSONObject(i);
                                            method = "addTextAlign";
                                            mPrinter.addTextAlign(Printer.ALIGN_LEFT);
                                            textData.append(" " + Constants.SL(bill_object.getString("sno")) +
                                                    Constants.Barcode(bill_object.getString("barcode"))
                                                    + Constants.Qty(bill_object.getString("qty")) + Constants.Mrp(bill_object.getString("item_rsp"))
                                                    + Constants.Dis(bill_object.getString("item_qty_disc"))
                                                    + Constants.Total(bill_object.getString("item_qty_payable_amount")));
                                            mPrinter.addText(textData.toString());
                                            textData.delete(0, textData.length());
                                            method = "addTextAlign";
                                            mPrinter.addTextAlign(Printer.ALIGN_LEFT);
                                            textData.append("   HSN " + bill_object.getString("hsn") + "  " + "Gst %" + bill_object.getString("gst_per") + " "
                                                    + " Gst Amt   " + bill_object.getString("gst_amount") + "\n");
                                            mPrinter.addText(textData.toString());
                                            textData.delete(0, textData.length());

                                            mPrinter.addTextAlign(Printer.ALIGN_LEFT);
                                            textData.append("    SM " + bill_object.getString("sm") + "           " + bill_object.getString("perticulars") + "\n");

                                            textData.append(Constants.dashed);
                                            mPrinter.addText(textData.toString());
                                            textData.delete(0, textData.length());
                                        }
                                    }
                                }
                            }
                        }


                        method = "addText";
                        mPrinter.addTextAlign(Printer.ALIGN_LEFT);
                        textData.append(" Gross Amount  : " + Constants.Gross(dataobject.getString("total_mrp")) + "\n");
                        textData.append(" Total Savings : " + Constants.TotalSavings(dataobject.getString("total_saving")) + "\n\n");

                        method = "addText";
                        mPrinter.addText(textData.toString());
                        textData.delete(0, textData.length());

                        method = "addText";
                        mPrinter.addTextAlign(Printer.ALIGN_CENTER);

                        method = "addTextSize";
                        mPrinter.addTextSize(2, 1);
                        method = "addText";
                        mPrinter.addText("Total Qty   :   " + dataobject.getString("total_qty") + "\n");
                        mPrinter.addText("Net Amount  :   " + dataobject.getString("total_payable") + "\n");
                /*textData.append("Total Qty     : " + dataobject.getString("total_qty")+"\n");
                textData.append("Net Amount    : " + dataobject.getString("total_payable")+"\n");*/
                        mPrinter.addText(textData.toString());
                        textData.delete(0, textData.length());
                        method = "addTextSize";

                        mPrinter.addTextSize(1, 1);
                        method = "addFeedLine";
                        mPrinter.addFeedLine(1);


                        method = "addText";
                        mPrinter.addText(textData.toString());
                        textData.delete(0, textData.length());

                        mPrinter.addTextAlign(Printer.ALIGN_LEFT);
                        textData.append(Constants.dashed);
                        mPrinter.addText(textData.toString());
                        textData.delete(0, textData.length());

                        if (dataobject.has("mop")) {
                            JSONArray mop = dataobject.getJSONArray("mop");
                           Log.e("Mop =====>" , String.valueOf(mop));
                            textData.delete(0, textData.length());
                            for (int L = 0; L < mop.length(); L++) {
                                JSONObject object = mop.getJSONObject(L);
                                method = "addTextAlign";
                                mPrinter.addTextAlign(Printer.ALIGN_LEFT);
                                method = "addText";
                                mPrinter.addText(" " + Constants.RecievedCashText(object.getString("paidtype")) + Constants.RecievedCash(object.getString("paidamount")) + "\n");
                            }
                        }


                        method = "addText";
                        mPrinter.addTextAlign(Printer.ALIGN_CENTER);
                        textData.append("\n" + "  Tax Details " + "\n");

                        method = "addText";
                        mPrinter.addText(textData.toString());
                        textData.delete(0, textData.length());
                        method = "addTextAlign";

                        mPrinter.addTextAlign(Printer.ALIGN_LEFT);
                        textData.append(Constants.dashed);
                        mPrinter.addText(textData.toString());
                        textData.delete(0, textData.length());

                        method = "addText";
                        mPrinter.addTextAlign(Printer.ALIGN_LEFT);
                        textData.append(" GST%   Taxable      CGST     SGST     IGST     " + "\n");
                        mPrinter.addText(textData.toString());
                        textData.delete(0, textData.length());

                        if (dataobject.has("gst_lines")) {
                            JSONArray TaxArray = new JSONArray(dataobject.getString("gst_lines"));
                            for (int j = 0; j < TaxArray.length(); j++) {
                                JSONObject taxoObject = TaxArray.getJSONObject(j);
                                JSONObject taxdata = new JSONObject();

                                method = "addText";
                                mPrinter.addTextAlign(Printer.ALIGN_LEFT);
                                textData.append(" " + Constants.GST(taxoObject.getString("gst_per").trim()) + Constants.Taxable(taxoObject.getString("taxable"))
                                        + Constants.CGST(taxoObject.getString("cgst")) + Constants.CGST(taxoObject.getString("sgst"))
                                        + Constants.CGST(taxoObject.getString("igst")) + "\n");
                                mPrinter.addText(textData.toString());
                                textData.delete(0, textData.length());
                            }
                            if (dataobject.has("gst_total")) {
                                JSONObject jsonObject = new JSONObject(dataobject.getString("gst_total"));
                                method = "addText";
                                textData.append(" Total  " + Constants.Taxable(jsonObject.getString("t_taxable")) + Constants.CGST(jsonObject.getString("t_cgst"))
                                        + Constants.CGST(jsonObject.getString("t_sgst")) + Constants.CGST(jsonObject.getString("t_igst")) + "\n");
                                mPrinter.addText(textData.toString());
                                textData.delete(0, textData.length());
                            }
                        }

                        method = "addText";
                        textData.append(Constants.dashed);
                        mPrinter.addText(textData.toString());
                        textData.delete(0, textData.length());

                        method = "addText";
                        mPrinter.addTextAlign(Printer.ALIGN_LEFT);
                        textData.append(" Biller : " + dataobject.getString("biller") + "\n");
                        mPrinter.addText(textData.toString());
                        textData.delete(0, textData.length());

                        method = "addText";
                        mPrinter.addTextAlign(Printer.ALIGN_CENTER);
                        textData.append("\n Delivery Slip Summary\n\n");
                        mPrinter.addText(textData.toString());
                        textData.delete(0, textData.length());

                        if (dataobject.has("ds_numbers")) {
                            JSONArray dslipArray = dataobject.getJSONArray("ds_numbers");
                           Log.e("DS NUMBERS =====>" , String.valueOf(dslipArray));
                            method = "addText";
                            mPrinter.addTextAlign(Printer.ALIGN_LEFT);
                            textData.append(" DS Number           Qty          Amount        ");
                            mPrinter.addText(textData.toString());
                            textData.delete(0, textData.length());
                            for (int m = 0; m < dslipArray.length(); m++) {
                                JSONObject object = dslipArray.getJSONObject(m);
                                method = "addTextAlign";
                                mPrinter.addTextAlign(Printer.ALIGN_LEFT);
                                method = "addText";
                                mPrinter.addText(" " + Constants.Deliveryslipnumber(object.getString("ds_no")) + DeliveryslipQty(object.getString("qty")) + DeliveryslipAmt(object.getString("ds_amount")));
                                textData.delete(0, textData.length());
                            }
                        }

                        method = "addText";
                        textData.append("\n" + Constants.dashed);
                        mPrinter.addText(textData.toString());
                        textData.delete(0, textData.length());


                        method = "addTextSize";
                        mPrinter.addTextSize(2, 2);
                        method = "addText";
                        mPrinter.addTextAlign(Printer.ALIGN_CENTER);
                        mPrinter.addText(dataobject.getString("memono") + "\n\n");

                        method = "addTextSize";

                        mPrinter.addTextSize(1, 1);

                        Bitmap logoData1 = BitmapFactory.decodeResource(getResources(), R.drawable.cash_paid);
                        final int barcodeWidth = 2;
                        final int barcodeHeight = 100;

                        if (mPrinter == null) {
                            return false;
                        }

                        try {
                            method = "addTextAlign";
                            mPrinter.addTextAlign(Printer.ALIGN_CENTER);

                            method = "addImage";
                            mPrinter.addImage(logoData1, 0, 0,
                                    logoData1.getWidth(),
                                    logoData1.getHeight(),
                                    Printer.COLOR_1,
                                    Printer.MODE_MONO,
                                    Printer.HALFTONE_DITHER,
                                    Printer.PARAM_DEFAULT,
                                    Printer.COMPRESS_AUTO);

                            method = "addFeedLine";
                            mPrinter.addFeedLine(1);
                        } catch (Epos2Exception eps) {
                            eps.getMessage();
                        }


                        if (dataobject.has("ds_number_last_numbers")) {
                            JSONArray dsArray = dataobject.getJSONArray("ds_number_last_numbers");
                           Log.e("DS NUMBERS =====>" , String.valueOf(dsArray));

                            for (int n = 0; n < dsArray.length(); n++) {
                                method = "addText";
                                mPrinter.addTextAlign(Printer.ALIGN_CENTER);

                                method = "addTextSize";
                                mPrinter.addTextSize(5, 5);
                                method = "addText";
                                mPrinter.addText("\n" + dsArray.get(n) + "\n");
                            }
                        }

                        method = "addCut";
                        mPrinter.addCut(Printer.CUT_FEED);

                        textData.delete(0, textData.length());
                        method = "addTextSize";

                        mPrinter.addTextSize(1, 1);
                        method = "addFeedLine";
                        mPrinter.addFeedLine(1);

                    }

                } catch (JSONException jo) {
                    jo.printStackTrace();
                } catch (Epos2Exception e) {
                    e.printStackTrace();
                } catch (Exception e) {
                   Log.e("Error Message ======>" , e.getMessage());
                    ShowMsg.showException(e, method, mContext);
                    return false;
                }
            }
        }
        textData = null;
        return true;
    }
    @Override
    protected void onDestroy() {
    /*    if(connection1!= null)
        unbindService(connection1);*/
        super.onDestroy();
    }
    @Override
    protected void onPause() {
        super.onPause();
    }

    private void PrintData(String cardNo, final int batchId){
        build = new StringBuilder();
        for (Model data : datalist) {
            if (build.toString().length() > 0) {
                build.append(Constants.PrintData(data.getDelivery_slip_id()));
            } else {
                build.append(Constants.PrintData1(data.getDelivery_slip_id()));
            }
        }
        JSONObject object = new JSONObject();
        try {
            object.put("bank_mapping_id", batchId);
            object.put("card_number", cardNo);
            object.put("amount", Float.parseFloat(NetAmount));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        if(Constants.isNetworkAvailable(CreateSaleBill.this)){
            RequestBody body = RequestBody.create(JSON, Constants.formdata1(build.toString(), cust_name.getText().toString(), cust_number.getText().toString(), object));
            dataPresenter.FinalData(Constants.BASE_URL + "/Sales/pre_sale_check",body);
            Constants.ProgressDialogShow(CreateSaleBill.this);
        }else{
            Constants.getToast(CreateSaleBill.this,"Please check your internet connection");
        }
    }

    @Override
    public void onDeliveryData(int code, final String res, String Id) {
        try {
            Constants.ProgressDialogDismiss();
            if (code == 200) {
                final JSONObject object = new JSONObject(res);
                if (object.has("success")) {
                    if (object.getInt("success") == 1) {
                        layout.setVisibility(View.VISIBLE);
                        data.setVisibility(View.VISIBLE);
                        generate_invoice.setVisibility(View.VISIBLE);
                        ds_Number.setText("");
                        JSONObject data = object.getJSONObject("data");
                        gross_amount.setText(Constants.IndianRupeesformat(data.getString("total_gross")));
                        discount_amount.setText(Constants.IndianRupeesformat(data.getString("total_promo_discount")));
                        round_off.setText(Constants.IndianRupeesformat(data.getString("round_off_amount")));
                        netamount.setText(Constants.IndianRupeesformat(data.getString("total_payable")));
                        NetAmount = data.getString("total_payable");
                        //build.append("{"+'"'+"delivery_slip_id"+'"'+":"+'"'+preferenceManager.getPrefix()+Id+'"'+","+'"'+"manual_discount"+'"'+":"+0+"}");
                        //var = true;
                        datalist.add(new Model(Id, 0));
                        //setArraylist.add(new Model(Id,0));
                        if (datalist.size() > 0) {
                            SetData(datalist);
                        }
                        //pluto_pay.setVisibility(View.VISIBLE);
                        //pluto_Print.setVisibility(View.VISIBLE);
                    } else {
                        layout.setVisibility(View.GONE);
                        generate_invoice.setVisibility(View.GONE);
                        runOnUiThread(() -> {
                            try {
                                Constants.getToast(CreateSaleBill.this, object.getString("msg"));
                                //Login.logout(CreateSaleBill.this);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        });
                    }
                }

            } else {
                runOnUiThread(() -> Constants.getToast(CreateSaleBill.this, res));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (NullPointerException io) {
            io.printStackTrace();
        }
    }
    @Override
    public void onDeliveryFail(final String fail) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
               Constants.ProgressDialogDismiss();
               Constants.getToast(CreateSaleBill.this, fail);
            }
        });
    }
    @Override
    public void onDeliveryDataRemove(int code, final String res) {
        try {
            Constants.ProgressDialogDismiss();
            if (code == 200) {
                final JSONObject obj = new JSONObject(res);
                if (obj.has("success")) {
                    if (obj.getInt("success") == 1) {
                        layout.setVisibility(View.VISIBLE);
                        ds_Number.setText("");
                        JSONObject data = obj.getJSONObject("data");
                        gross_amount.setText(Constants.IndianRupeesformat(data.getString("total_gross")));
                        discount_amount.setText(Constants.IndianRupeesformat(data.getString("total_promo_discount")));
                        round_off.setText(Constants.IndianRupeesformat(data.getString("round_off_amount")));
                        netamount.setText(Constants.IndianRupeesformat(data.getString("total_payable")));
                        NetAmount = data.getString("total_payable");
                        if (datalist.size() > 0) {
                            SetData(datalist);
                        }
                    } else {
                        layout.setVisibility(View.GONE);
                        //bank_details.setVisibility(View.GONE);
                        runOnUiThread(() -> {
                            try {
                                Constants.getToast(CreateSaleBill.this, obj.getString("msg"));
                                Login.logout(CreateSaleBill.this);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        });
                    }
                }
            } else {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Constants.getToast(CreateSaleBill.this, res);
                    }
                });
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (NullPointerException io) {
            io.printStackTrace();
        }
    }

    @Override
    public void onDeliveryFailRemove(final String fail) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Constants.ProgressDialogDismiss();
                Constants.getToast(CreateSaleBill.this,fail);
            }
        });
    }

    @Override
    public void onLogoutData(int code, final String remove) {
        try {
            Constants.ProgressDialogDismiss();
            if (code == 200) {
                final JSONObject object = new JSONObject(remove);
                //stores = new ArrayList<>();
                if (object.has("success")) {
                    if (object.getInt("success") == 1) {
                        //JSONObject data = object.getJSONObject("data");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    Constants.getToast(CreateSaleBill.this, object.getString("msg"));
                                    preferenceManager.setUserId("");
                                    preferenceManager.setLogged(false);
                                    preferenceManager.setCustToken("");
                                    preferenceManager.setBLUETOOTH("");
                                    Login.logout(CreateSaleBill.this);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    } else {
                        runOnUiThread(() -> {
                            try {
                                Constants.getToast(CreateSaleBill.this, object.getString("msg"));
                                Login.logout(CreateSaleBill.this);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        });
                    }
                }
            }else{
                runOnUiThread(() -> Constants.getToast(CreateSaleBill.this,remove));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }catch (NullPointerException np){
            np.printStackTrace();
        }
    }

    @Override
    public void onLogoutFail(final String fail) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Constants.ProgressDialogDismiss();
                Constants.getToast(CreateSaleBill.this,fail);
            }
        });
    }

    @Override
    public void onFinalData(int code, String finalData) {
        try{
            Constants.ProgressDialogDismiss();
            bankdialog.dismiss();
            if (code == 200) {
                pluto_Print.setVisibility(View.VISIBLE);
                generate_invoice.setVisibility(View.GONE);
                data.setVisibility(View.INVISIBLE);
                ds_list.setAdapter(null);
                datalist.clear();
                cust_name.setText("");
                cust_number.setText("");
                responseobj = new JSONObject(finalData);
                if(responseobj.has("success")) {
                    if (responseobj.getInt("success") == 1) {
                            updateButtonState(false);
                        if (!runPrintReceiptSequence()) {
                            updateButtonState(true);
                        }
                    } else {
                        runOnUiThread(() -> {
                            try {
                                Constants.getToast(CreateSaleBill.this, responseobj.getString("msg"));
                                Login.logout(CreateSaleBill.this);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        });
                    }
                }
            } else {
                Constants.getToast(CreateSaleBill.this, finalData);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (NullPointerException np) {
            np.printStackTrace();
        }
    }

    @Override
    public void onFinalFail(final String finalFail) {
        runOnUiThread(() -> {
            Constants.ProgressDialogDismiss();
            Constants.getToast(CreateSaleBill.this,finalFail);
            bankdialog.dismiss();
            pluto_Print.setVisibility(View.GONE);
            generate_invoice.setVisibility(View.VISIBLE);
            data.setVisibility(View.VISIBLE);
        });
    }

    @Override
    public void onCustomerName(int code, final String name) {
        if(code == 200){
            runOnUiThread(() -> {
                try{
                    final JSONObject object = new JSONObject(name);
                    if(object.has("success")){
                        if(object.getInt("success") == 1){
                            JSONObject jsonObject = object.getJSONObject("data");
                            //if(jsonObject.getString("customer_name"))
                            if(jsonObject.getString("customer_name").isEmpty()){
                                cust_name.setText("");
                            }else {
                                cust_name.setText(jsonObject.getString("customer_name"));
                                ds_Number.requestFocus();
                            }
                        }else{

                        }
                    }
                }catch(JSONException e){
                    e.printStackTrace();
                }
            });
        }else{
            runOnUiThread(() -> Constants.getToast(CreateSaleBill.this,name));
        }
    }

    @Override
    public void onCustomerNameFail(String fail) {
        runOnUiThread(() -> {
            //cust_name.setText(name);
        });
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event){
        if(v.getId() == R.id.ds_Number) {
            if (TextUtils.isEmpty(ds_Number.getText().toString())) {
                Constants.getToast(CreateSaleBill.this, "Enter Delivery Slip Id");
            } else {
                if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE) || (actionId == EditorInfo.IME_ACTION_NEXT) || (actionId == EditorInfo.IME_ACTION_GO)) {
                    Log.e("Event =============>","");
                    DsData(preferenceManager.getPrefix() + ds_Number.getText().toString());
                    Constants.hideKeyboard(this);
                }
            }
        }else if(v.getId() == R.id.last_four_digits){
            if (BankName.equalsIgnoreCase("Select Bank") && last_four_digits.getText().toString().length() == 0) {
                Constants.getToast(CreateSaleBill.this, "Please Select Bank and Enter last four digits");
            } else if (BankName.equalsIgnoreCase("Select Bank")) {
                Constants.getToast(CreateSaleBill.this, "Please Select Bank ");
            } else if (last_four_digits.getText().toString().length() == 0) {
                Constants.getToast(CreateSaleBill.this, "Enter last four digits");
            } else if (last_four_digits.getText().toString().length() == 4) {
                if (Constants.isNetworkAvailable(CreateSaleBill.this)) {
                    Constants.hideSoftKeyBoardOnTabClicked(v, CreateSaleBill.this);
                    PrintData(last_four_digits.getText().toString(), BankId);
                }else{
                    Constants.getToast(CreateSaleBill.this,"Please check your internet connection");
                }
            }
        }
        return false;
    }
}
