package w.soulofpluto.posstock;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.Html;
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.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.ItemTouchHelper;
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.google.android.material.snackbar.Snackbar;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static w.soulofpluto.posstock.Constants.DeliveryslipAmt;
import static w.soulofpluto.posstock.Constants.DeliveryslipQty;
import static w.soulofpluto.posstock.Constants.JSON;
import static w.soulofpluto.posstock.Constants.Logout;

/*
 Create by Ramesh Babu
*/

public class CreateDeliverySlip extends AppCompatActivity implements AdapterView.OnItemClickListener, ReceiveListener, TextView.OnEditorActionListener {
    Toolbar createDeliverySlip_toolbar;
    EditText barcode_enter, empId;
    List<CreateResponse> arrayList;
    LinearLayout header_items;
    CheckBox checkBox;
    PreferenceManager preferenceManager;
    RecyclerView deliveryslip_list;
    TextView totalItems, totalMrp, totalDis, totalNetMrp;
    ArrayList<Barcode> list;
    Button valid, valid_print;
    Boolean print = false;
    public static Printer mPrinter = null;
    DeliverySlipAdapter deliverySlipAdapter;
    List<CreateResponse.Datum> versionList;
    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;
    Menu globalMenuItem;
    Dialog dialog;
    JSONObject responseobj;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        setContentView(R.layout.activity_createdeliveryslip);
        createDeliverySlip_toolbar = findViewById(R.id.createdeliveryslip_toolbar);
        checkBox      = findViewById(R.id.checked);
        barcode_enter = findViewById(R.id.barcode_enter);
        deliveryslip_list = findViewById(R.id.deliveryslip_list);
        totalItems = findViewById(R.id.totalItems);
        totalMrp = findViewById(R.id.totalMrp);
        totalDis = findViewById(R.id.totalDis);
        totalNetMrp = findViewById(R.id.totalNetMrp);
        empId = findViewById(R.id.emp_id);
        valid = findViewById(R.id.valid);
        header_items = findViewById(R.id.header_items);
        valid_print = findViewById(R.id.valid_print);
        setSupportActionBar(createDeliverySlip_toolbar);
        getSupportActionBar().setTitle(getResources().getString(R.string.create_title));
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        preferenceManager = new PreferenceManager(this);
        arrayList = new ArrayList<>();
        list = new ArrayList<>();
        versionList = new ArrayList<>();
        empId.setText(preferenceManager.getUserId());
        checkBox.setChecked(true);
        barcode_enter.requestFocus();
        barcode_enter.setOnEditorActionListener(this);

        Log.e("Access Token ====> ", preferenceManager.getCustToken());

        valid_print.setOnClickListener(view -> {
            if(preferenceManager.getBLUETOOTH().length()>0) {
                if (list.size() > 0) {
                    //print = true;
                    if (Constants.isNetworkAvailable(CreateDeliverySlip.this)) {
                        Constants.ProgressDialogShow(CreateDeliverySlip.this);
                        GenerateDeliverySlip("save", barcode_enter.getText().toString().trim(),  "Y", false);
                    } else {
                        Constants.getToast(CreateDeliverySlip.this, getResources().getString(R.string.connection));
                    }
                } else {
                    Constants.getToast(CreateDeliverySlip.this, "Please Scan Barcode Items");
                }
            }else{
                Constants.getToast(CreateDeliverySlip.this,"Please Connect Bluetooth Printer");
            }
        });


        valid.setOnClickListener(view -> {
            if (list.size() > 0) {
                if (Constants.isNetworkAvailable(CreateDeliverySlip.this)) {
                    Constants.ProgressDialogShow(CreateDeliverySlip.this);
                    GenerateDeliverySlip("scan", barcode_enter.getText().toString().trim(), "Y",true);
                } else {
                    Constants.getToast(CreateDeliverySlip.this, getResources().getString(R.string.connection));
                }
            } else {
                Constants.getToast(CreateDeliverySlip.this, "Please Scan Barcode Items");
            }
        });
        barcode_enter.addTextChangedListener(new Checked());

        new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.RIGHT) {
            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
                return false;
            }
            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
                final CreateResponse.Datum deletedCourse = versionList.get(viewHolder.getAdapterPosition());
                final int position = viewHolder.getAdapterPosition();
                versionList.remove(viewHolder.getAdapterPosition());
                deliverySlipAdapter.notifyItemRemoved(viewHolder.getAdapterPosition());
                for (Barcode barcode : list) {
                    if (barcode.getBarcode().equalsIgnoreCase(deletedCourse.getBarcode())) {
                        list.remove(barcode);
                        break;
                    }
                }
                if(list.size()<1){
                  header_items.setVisibility(View.GONE);
                    if(checkBox.isChecked()){
                        barcode_enter.requestFocus();
                    }else{
                        empId.setText("");
                        empId.requestFocus();
                    }
                }
                if (Constants.isNetworkAvailable(CreateDeliverySlip.this)) {
                    Constants.ProgressDialogShow(CreateDeliverySlip.this);
                    GenerateDeliverySlip("scan", "", "N",false);
                } else {
                    Constants.getToast(CreateDeliverySlip.this, getResources().getString(R.string.connection));
                }
            }
        }).attachToRecyclerView(deliveryslip_list);
        super.onCreate(savedInstanceState);
    }

    private boolean runPrintReceiptSequence() {
        if (!initializeObject()) {
            Log.e("initialize Object >>", "runPrintReceipt");
            return false;
        }
        if (!createReceiptData()) {
            System.out.println("runPrintReceipt1");
            finalizeObject();
            return false;
        }
        if (!printData()) {
            finalizeObject();
            Log.e("Print Data ====>", "runPrintReceipt2");
            return false;
        }
        return true;
    }

    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);
            System.out.println("Shared Preferences Bluetooth ========>" + preferenceManager.getBLUETOOTH());
        } catch (Exception e) {
            ShowMsg.showException(e, "connect", CreateDeliverySlip.this);
            return false;
        }
        try {
            mPrinter.beginTransaction();
            isBeginTransaction = true;
        } catch (Exception e) {
            ShowMsg.showException(e, "beginTransaction", CreateDeliverySlip.this);
        }
        if (isBeginTransaction == false) {
            try {
                mPrinter.disconnect();
            } catch (Epos2Exception e) {
                // Do nothing
                return false;
            }
        }
        return true;
    }

    public void Logout(String Url) {
        final OkHttpClient client = new OkHttpClient();
        client.setConnectTimeout(240, TimeUnit.SECONDS);
        client.setReadTimeout(240, TimeUnit.SECONDS);
        client.setWriteTimeout(240, TimeUnit.SECONDS);
        final Request request = new Request.Builder()
                .url(Url)
                .get()
                .addHeader("Content-Type", "application/json")
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                Constants.ProgressDialogDismiss();
            }

            @Override
            public void onResponse(Response response) throws IOException {
                try {
                    Constants.ProgressDialogDismiss();
                    final String res = response.body().string();
                    if (response.code() == 200) {
                        Log.e("Dashboard Logout ", res);
                        JSONObject jsonObject = new JSONObject(res);
                        if (jsonObject.has("success")) {
                            if (jsonObject.getInt("success") == 1) {
                                preferenceManager.setUserId("");
                                preferenceManager.setLogged(false);
                                preferenceManager.setCustToken("");
                                preferenceManager.setStoreId("");
                                preferenceManager.setBLUETOOTH("");
                                Login.logout(CreateDeliverySlip.this);
                            } else if(jsonObject.has("msg")) {
                                Constants.getToast(CreateDeliverySlip.this, jsonObject.getString("msg"));
                            }
                        }
                    } else {
                        runOnUiThread(() -> Constants.getToast(CreateDeliverySlip.this, res));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (NullPointerException np) {
                    np.printStackTrace();
                }
                }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
            case R.id.dashboard_logout:
                if (Constants.isNetworkAvailable(CreateDeliverySlip.this)) {
                    Logout(Logout + preferenceManager.getUserId());
                    Constants.ProgressDialogShow(CreateDeliverySlip.this);
                } else {
                    Constants.getToast(CreateDeliverySlip.this, getResources().getString(R.string.connection));
                }
                try {
                    Discovery.stop();
                    break;
                } catch (Epos2Exception e1) {
                    System.out.println("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) {
                    System.out.println("Output =====>" + e1.getMessage());
                }
                break;
        }
        return super.onOptionsItemSelected(item);
    }

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


    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 boolean printData() {
        if (mPrinter == null) {
            return false;
        }
        if (!connectPrinter()) {
            return false;
        }
        PrinterStatusInfo status = mPrinter.getStatus();
        dispPrinterWarnings(status);
        if (!isPrintable(status)) {
            ShowMsg.showMsg(makeErrorMessage(status), CreateDeliverySlip.this);
            try {
                mPrinter.disconnect();
            } catch (Exception ex) {
                // Do nothing
            }
            return false;
        }
        try {
            mPrinter.sendData(Printer.PARAM_DEFAULT);
        } catch (Exception e) {
            ShowMsg.showException(e, "sendData", CreateDeliverySlip.this);
            try {
                mPrinter.disconnect();
            } catch (Exception ex) {
                // Do nothing
            }
            return false;
        }
        return true;
    }
    private void finalizeObject() {
        if (mPrinter == null) {
            return;
        }
        mPrinter.clearCommandBuffer();
        mPrinter.setReceiveEventListener(null);
        mPrinter = null;
    }

    void getPrint() {
        try {
            if (responseobj.has("data")) {
                System.out.println("Response Data =============>" + responseobj);
                JSONObject dataobj = responseobj.getJSONObject("data");
                mPrinter.addTextSize(2, 2);
                mPrinter.addTextAlign(Printer.ALIGN_CENTER);
                mPrinter.addText(" * ESTIMATION SLIP * " + "\n");
                mPrinter.addTextSize(1, 1);
                mPrinter.addFeedLine(1);
                mPrinter.addTextAlign(Printer.ALIGN_LEFT);
                mPrinter.addText("Date : " + dataobj.getString("dsdate") + "\n");
                mPrinter.addTextAlign(Printer.ALIGN_LEFT);
                mPrinter.addText(Constants.dashed);
                if (dataobj.has("ds_lines")) {
                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                        mPrinter.addTextAlign(Printer.ALIGN_LEFT);
                        mPrinter.addText("SL Barcode    Qty MRP       Disc     Amount    " + "\n");
                        mPrinter.addTextAlign(Printer.ALIGN_LEFT);
                        mPrinter.addText(Constants.dashed);
                        JSONObject da = dataobj.getJSONObject("ds_lines");
                        Iterator<String> keys = da.keys();
                        while (keys.hasNext()) {
                            String key = keys.next();
                            if (da.get(key) instanceof JSONArray) {
                                // do something with jsonObject here
                                System.out.println("Connection  =====>" + da);
                                System.out.println("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);
                                    mPrinter.addTextAlign(Printer.ALIGN_LEFT);
                                    mPrinter.addText(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("qty_disc"))
                                            + Constants.Total(bill_object.getString("qty_amount_after_discount")));
                                    mPrinter.addTextAlign(Printer.ALIGN_LEFT);
                                    mPrinter.addText("   SM : " + bill_object.getString("sm") + "  " + bill_object.getString("section") + "\n");
                                    mPrinter.addText(Constants.dashed);
                                 }
                            }
                        }
                    }
                }
                mPrinter.addTextAlign(Printer.ALIGN_LEFT);
                mPrinter.addText("Gross Amount   : " + Constants.Gross(dataobj.getString("total_grossamount")) + "\n");
                mPrinter.addText("Total Discount : " + Constants.TotalSavings(dataobj.getString("total_promodisc")) + "\n\n");
                mPrinter.addTextAlign(Printer.ALIGN_CENTER);
                mPrinter.addTextSize(2, 2);
                mPrinter.addText("Total Qty   :   " + dataobj.getString("total_qty") + "\n");
                mPrinter.addText("Net Payable  :   " + dataobj.getString("total_payable") + "\n");
                mPrinter.addTextSize(1, 1);
                mPrinter.addFeedLine(1);
                mPrinter.addTextAlign(Printer.ALIGN_CENTER);
                mPrinter.addText(" Biller : " + dataobj.getString("biller") + "\n");
                mPrinter.addFeedLine(1);
                mPrinter.addBarcode(dataobj.getString("dsno"),
                        Printer.BARCODE_CODE39,
                        Printer.HRI_BELOW,
                        Printer.FONT_A,
                        2,
                        100);
                mPrinter.addFeedLine(2);
                mPrinter.addTextSize(4, 4);
                mPrinter.addTextAlign(Printer.ALIGN_CENTER);
                mPrinter.addText(dataobj.getString("dsno_last_number") + "\n\n");
                mPrinter.addCut(Printer.CUT_FEED);
                mPrinter.addTextSize(1, 1);
                mPrinter.addFeedLine(1);
            }
        } catch (JSONException jo) {
            jo.printStackTrace();
        } catch (Epos2Exception e) {
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("Error Message ======>" + e.getMessage());
            //ShowMsg.showException(e, method, CreateDeliverySlip.this);
        }
    }

    private boolean createReceiptData() {
        String method = "";
        StringBuilder textData = new StringBuilder();
        Constants.ProgressDialogDismiss();
        if (print) {
            print = false;
            if (mPrinter == null) {
                return false;
            }
            getPrint();

        } else {
            for (int k = 0; k < 2; k++) {
                if (mPrinter == null) {
                    return false;
                }
                getPrint();
            }
            runOnUiThread(() -> {
                valid.setVisibility(View.GONE);
                valid_print.setVisibility(View.GONE);
                arrayList.clear();
                list.clear();
                deliveryslip_list.setAdapter(null);
                totalItems.setText("");
                totalNetMrp.setText("");
                totalMrp.setText("");
                totalDis.setText("");
            });
        }
        mPrinter = null;
        return true;
    }


    private boolean initializeObject() {
        try {
            mPrinter = new Printer(1, 6, CreateDeliverySlip.this);
        } catch (Exception e) {
            ShowMsg.showException(e, "Printer", CreateDeliverySlip.this);
            Constants.ProgressDialogDismiss();
            return false;
        }
        mPrinter.setReceiveEventListener(this);
        return true;
    }


    private void updateButtonState(boolean state) {
        valid.setEnabled(state);
        System.out.println("Data State Enables===>" + state);
    }


    @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"));
            //System.out.println("Bluetooth Target =====>"+item.get("Target"));
            dialog.dismiss();
            preferenceManager.setBLUETOOTH(item.get("Target"));
            invalidateOptionsMenu();
        } catch (NullPointerException np) {
            np.printStackTrace();
        }
    }

    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 void disconnectPrinter() {
        if (mPrinter == null) {
            return;
        }
        try {
            mPrinter.endTransaction();
        } catch (final Exception e) {

        }
        try {
            mPrinter.disconnect();
        } catch (final Exception e) {
        }
        finalizeObject();
    }

    @Override
    public void onPtrReceive(Printer printer, final int code, final PrinterStatusInfo printerStatusInfo, String s) {
        runOnUiThread(new Runnable() {
            @Override
            public synchronized void run() {
                ShowMsg.showResult(code, makeErrorMessage(printerStatusInfo), CreateDeliverySlip.this);

                dispPrinterWarnings(printerStatusInfo);

                updateButtonState(true);

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

    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(CreateDeliverySlip.this, warningsMsg);
        }
        // edtWarnings.setText(warningsMsg);
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if(v.getId() == R.id.barcode_enter) {
            if (TextUtils.isEmpty(barcode_enter.getText().toString())) {
                Constants.getToast(CreateDeliverySlip.this, "Enter Barcode");
            } 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 =============>","");
                    Constants.hideKeyboard(this);
                    if(Constants.isNetworkAvailable(this)){
                        GenerateDeliverySlip("scan", barcode_enter.getText().toString().trim(), "N", false);
                        Constants.ProgressDialogShow(CreateDeliverySlip.this);
                    }else {
                        Constants.getToast(CreateDeliverySlip.this,"Please check internet connection");
                    }
                }
            }
        }
        return false;
    }

    public class Checked implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence val, int i, int i1, int i2) {
            try {
                if (val.toString().length() > 0) {
                    if (val.toString().contains("\n")) {
                        if (Constants.isNetworkAvailable(CreateDeliverySlip.this)) {
                            Constants.ProgressDialogShow(CreateDeliverySlip.this);
                            GenerateDeliverySlip("scan", val.toString().trim(), "N",false);
                        } else {
                            Constants.getToast(CreateDeliverySlip.this, getResources().getString(R.string.connection));
                        }
                    }
                }

            } catch (NullPointerException np) {
                np.printStackTrace();
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {
        }

    }

    public void GenerateDeliverySlip(final String scan, String trim,  String app, final boolean var) {
        JSONObject object = new JSONObject();
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                object.put(getResources().getString(R.string.action), scan);
                object.put(getResources().getString(R.string.promotions), "N");
                object.put(getResources().getString(R.string.apply_promotion),app);
                JSONArray jsonArray = new JSONArray();
                JSONObject jsonObject = null;
                if (list.size() > 0) {
                    for (Barcode b : list) {
                        jsonObject = new JSONObject();
                        jsonObject.put(getResources().getString(R.string.barcode_name), b.barcode);
                        jsonObject.put(getResources().getString(R.string.qty_name), b.qty);
                        jsonObject.put(getResources().getString(R.string.empid), b.empId);
                        jsonArray.put(jsonObject);
                    }
                }
                Log.e("Test", trim);
                if (trim.length() > 0) {
                    jsonObject = new JSONObject();
                    jsonObject.put(getResources().getString(R.string.barcode_name), trim);
                    jsonObject.put(getResources().getString(R.string.qty_name), 1);
                    jsonObject.put(getResources().getString(R.string.empid), empId.getText().toString());
                    jsonArray.put(jsonObject);
                }
                if (list.size() > 0 || trim.length() > 0) {
                    object.put(getResources().getString(R.string.items), jsonArray);
                    //object.put(getResources().getString(R.string.android_version),Constants.VERSION);
                    Log.e("Search", object.toString());
                    RequestBody body = RequestBody.create(JSON, object.toString());
                    final OkHttpClient client = new OkHttpClient();
                    client.setConnectTimeout(250, TimeUnit.SECONDS);
                    client.setReadTimeout(250, TimeUnit.SECONDS);
                    client.setWriteTimeout(250, TimeUnit.SECONDS);
                    Request request = new Request.Builder()
                            .url(Constants.GenerateSlip)
                            .post(body)
                            .addHeader(Constants.Type, Constants.App_json)
                            .addHeader(getResources().getString(R.string.accesstoken), preferenceManager.getCustToken())
                            .addHeader(getResources().getString(R.string.storeidtoken), preferenceManager.getStoreId())
                            .build();
                    client.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(Request request, final IOException e) {
                            runOnUiThread(() -> {
                                Constants.getToast(CreateDeliverySlip.this, e.getMessage());
                                Constants.ProgressDialogDismiss();
                            });
                        }
                        @Override
                        public void onResponse(final com.squareup.okhttp.Response response) throws IOException {
                            try {
                                Constants.ProgressDialogDismiss();
                                final String Response = response.body().string();
                                Log.e("Barcode Search", Response);
                                Handler handler = new Handler(Looper.getMainLooper());
                                handler.post(() -> {
                                    try {
                                        if(response.code() == 200){
                                            responseobj = new JSONObject(Response);
                                            if(responseobj.getInt("success") == 1){
                                                if(scan.equalsIgnoreCase("save")){
                                                    valid_print.setVisibility(View.GONE);
                                                    valid.setVisibility(View.VISIBLE);
                                                    header_items.setVisibility(View.GONE);
                                                    if(responseobj.has("data")){
                                                        updateButtonState(false);
                                                        if (!runPrintReceiptSequence()) {
                                                            updateButtonState(true);
                                                        }
                                                    }
                                                }else if(var){
                                                    header_items.setVisibility(View.VISIBLE);
                                                    valid_print.setVisibility(View.VISIBLE);
                                                    valid.setVisibility(View.GONE);
                                                    if (responseobj.has("data")) {
                                                        if (barcode_enter.getText().toString().length() > 0)
                                                            list.add(new Barcode(barcode_enter.getText().toString().trim(), 1, empId.getText().toString()));
                                                        barcode_enter.setText("");
                                                        barcode_enter.requestFocus();
                                                        versionList = new Gson().fromJson(String.valueOf(responseobj.getJSONArray(getResources().getString(R.string.data))),
                                                                new TypeToken<List<CreateResponse.Datum>>() {
                                                                }.getType());
                                                        Log.e("Response =====>", String.valueOf(responseobj.getJSONArray(getResources().getString(R.string.data))));
                                                        deliveryslip_list.setLayoutManager(new LinearLayoutManager(CreateDeliverySlip.this));
                                                        deliverySlipAdapter = new DeliverySlipAdapter(CreateDeliverySlip.this, versionList);
                                                        deliveryslip_list.setAdapter(deliverySlipAdapter);
                                                    }
                                                    totalItems.setText(Html.fromHtml(Constants.getTotalItems(responseobj.getString(getResources().getString(R.string.totalqty)))));
                                                    totalMrp.setText(Html.fromHtml(Constants.getTotalMRP(Constants.IndianRupeesFormat(responseobj.getString(getResources().getString(R.string.netpayable))))));
                                                    if(checkBox.isChecked()){
                                                       barcode_enter.requestFocus();
                                                    }else{
                                                       empId.setText("");
                                                       empId.requestFocus();
                                                    }
                                                    Log.e("total Qty ========>", responseobj.getString(getResources().getString(R.string.totalqty)));
                                                    Log.e("total NetPayable ===>", responseobj.getString(getResources().getString(R.string.netpayable)));
                                                } else {
                                                    valid_print.setVisibility(View.GONE);
                                                    valid.setVisibility(View.VISIBLE);
                                                    header_items.setVisibility(View.VISIBLE);
                                                    //List<CreateResponse> versionList = new Gson().fromJson(Response, new TypeToken<List<CreateResponse>>() {}.getType());
                                                    if (responseobj.has("data")) {
                                                        if (barcode_enter.getText().toString().length() > 0)
                                                            list.add(new Barcode(barcode_enter.getText().toString().trim(), 1, empId.getText().toString()));
                                                        barcode_enter.setText("");
                                                        barcode_enter.requestFocus();
                                                        versionList = new Gson().fromJson(String.valueOf(responseobj.getJSONArray(getResources().getString(R.string.data))),
                                                                new TypeToken<List<CreateResponse.Datum>>() {
                                                                }.getType());
                                                        Log.e("Response =====>", String.valueOf(responseobj.getJSONArray(getResources().getString(R.string.data))));
                                                        deliveryslip_list.setLayoutManager(new LinearLayoutManager(CreateDeliverySlip.this));
                                                        deliverySlipAdapter = new DeliverySlipAdapter(CreateDeliverySlip.this, versionList);
                                                        deliveryslip_list.setAdapter(deliverySlipAdapter);
                                                    }
                                                    totalItems.setText(Html.fromHtml(Constants.getTotalItems(responseobj.getString(getResources().getString(R.string.totalqty)))));
                                                    totalMrp.setText(Html.fromHtml(Constants.getTotalMRP(Constants.IndianRupeesFormat(responseobj.getString(getResources().getString(R.string.netpayable))))));
                                                    if(checkBox.isChecked()){
                                                       barcode_enter.requestFocus();
                                                    }else{
                                                       empId.setText("");
                                                       empId.requestFocus();
                                                    }
                                                    Log.e("total Qty ========>", responseobj.getString(getResources().getString(R.string.totalqty)));
                                                    Log.e("total NetPayable ===>", responseobj.getString(getResources().getString(R.string.netpayable)));
                                                }
                                            } else if (responseobj.getInt("success") == 3) {
                                                runOnUiThread(() -> {
                                                    try {
                                                        Constants.getToast(CreateDeliverySlip.this, responseobj.getString(getResources().getString(R.string.msg)));
                                                        Login.logout(CreateDeliverySlip.this);
                                                    } catch (JSONException e) {
                                                        e.printStackTrace();
                                                    }
                                                });
                                            } else if (responseobj.has(getResources().getString(R.string.msg))) {
                                                runOnUiThread(() -> {
                                                    try {
                                                        Constants.getToast(CreateDeliverySlip.this, responseobj.getString(getResources().getString(R.string.msg)));
                                                        //barcode_enter.setText("");
                                                        barcode_enter.requestFocus();
                                                    } catch (JSONException e) {
                                                        e.printStackTrace();
                                                    }
                                                });
                                            }
                                        }else {
                                            runOnUiThread(() -> Constants.getToast(CreateDeliverySlip.this,Response));
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                });
                            } catch (NullPointerException io) {
                                io.printStackTrace();
                            } finally {
                                response.body().close();
                            }
                        }
                    });
                } else {
                    Constants.ProgressDialogDismiss();
                    Constants.getToast(CreateDeliverySlip.this, "No Barcode Scanned Items");
                    totalItems.setText("");
                    totalMrp.setText("");
                    valid.setVisibility(View.GONE);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }catch (NullPointerException npe){
            npe.printStackTrace();
        }
    }


    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{
            if (initial) {
                Discovery.stop();
                initial = false;
                Discovery.start(this, mFilterOption, mDiscoveryListener);
                // Constants.ProgressDialogShow(this);
            } else {
                try {
                    Discovery.start(this, mFilterOption, mDiscoveryListener);
                    Constants.ProgressDialogShow(this);
                } catch (Exception e) {
                    //Log.e("Exception =======>",e.getMessage());
                }
            }
        } catch (Epos2Exception e) {
            try {
                Discovery.start(this, mFilterOption, mDiscoveryListener);
            } catch (Epos2Exception e1) {
                e1.getMessage();
            }
            if (e.getErrorStatus() != Epos2Exception.ERR_PROCESSING) {
                ShowMsg.showException(e, "stop", CreateDeliverySlip.this);
                return;
            }
        } finally {
        }
        refresh_bluetooth.setOnClickListener(v -> restartDiscovery());
    }

    private void restartDiscovery() {
        while (true) {
            try {
                Discovery.stop();
                break;
            } catch (Epos2Exception e) {
                if (e.getErrorStatus() != Epos2Exception.ERR_PROCESSING) {
                    ShowMsg.showException(e, "stop", CreateDeliverySlip.this);
                    return;
                }
            }
        }
        mPrinterList.clear();
        mPrinterListAdapter.notifyDataSetChanged();
        try {
            Discovery.start(this, mFilterOption, mDiscoveryListener);
            Constants.ProgressDialogShow(this);
        } catch (Exception e) {
            ShowMsg.showException(e, "stop", CreateDeliverySlip.this);
        }
    }

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


}
