package w.soulofpluto.posstock;

import android.app.AlertDialog;
import android.app.Dialog;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import static w.soulofpluto.posstock.Constants.JSON;

 /*
  Create by Ramesh Babu Puvvadi
 */

public class StockOutWordActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
    Toolbar                stockOut_toolbar;
    PreferenceManager      preferenceManager;
    String                 Response, uomText;
    ArrayList<State>       stateArrayList;
    ArrayList<Format>      formatArrayList;
    ArrayList<StoreFormat> storeFormatArrayList;
    Spinner                state_spinner, format_spinner, location_spinner, uom_spinner;
    int                    state_Id, format_Id, location_Id;
    EditText               qty, barcode;
    String                 Store_Point_Id;
    String[]               uom = {"Units", "Meters"};
    ArrayList<StockBarcode> StockBarcodeArrayList;
    ArrayList<Plans>       arrayList;
    RecyclerView           stockOutWord_recyclerView;
    PlanDetailsAdapter     planDetailsAdapter;
    Dialog                 dialog;
    Menu                   menu;
    TextView               total_boxes, total_lines, total_qty;
    HashMap<Integer,ArrayList<Plans>> hashMap;
    MediaPlayer            mp;
    int                    max = 10;
    int                    min = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
       setContentView(R.layout.activity_stockout);
       setUI();
       if (Constants.isNetworkAvailable(StockOutWordActivity.this)) {
           getCall();
           ArrayAdapter<String> adapter = new ArrayAdapter<>(StockOutWordActivity.this, android.R.layout.simple_list_item_1, uom);
           uom_spinner.setAdapter(adapter);
       } else {
           runOnUiThread(() -> Constants.getToast(StockOutWordActivity.this, getResources().getString(R.string.nonetwork)));
       }
       super.onCreate(savedInstanceState);
    }

    public void setUI() {
        total_boxes               = findViewById(R.id.total_boxes);
        total_lines               = findViewById(R.id.total_lines);
        total_qty                 = findViewById(R.id.total_qty);
        stockOut_toolbar          = findViewById(R.id.stockout_toolbar);
        state_spinner             = findViewById(R.id.state_spinner);
        format_spinner            = findViewById(R.id.format_spinner);
        location_spinner          = findViewById(R.id.location_spinner);
        uom_spinner               = findViewById(R.id.uom);
        barcode                   = findViewById(R.id.barcode);
        qty                       = findViewById(R.id.qty);
        preferenceManager         = new PreferenceManager(StockOutWordActivity.this);
        stateArrayList            = new ArrayList<>();
        formatArrayList           = new ArrayList<>();
        storeFormatArrayList      = new ArrayList<>();
        StockBarcodeArrayList     = new ArrayList<>();
        arrayList                 = new ArrayList<>();
        hashMap                   = new HashMap<>();
        stockOutWord_recyclerView = findViewById(R.id.stockOutWord_recyclerView);
        setSupportActionBar(stockOut_toolbar);
        getSupportActionBar()    .setTitle(getResources().getString(R.string.stock_out));
        getSupportActionBar()    .setDisplayHomeAsUpEnabled(true);
        state_spinner            .setOnItemSelectedListener(this);
        format_spinner           .setOnItemSelectedListener(this);
        uom_spinner              .setOnItemSelectedListener(this);
        location_spinner         .setOnItemSelectedListener(this);
        barcode                  .requestFocus();
        barcode                  .addTextChangedListener(new Checked());
        barcode                  .setOnFocusChangeListener((view, hasFocus) -> {
          if(!hasFocus){
          }else{
            Constants.hideSoftKeyboard(barcode, StockOutWordActivity.this);
          }
        });
    }

    public void getNotification() {
        runOnUiThread(() -> {
            mp = MediaPlayer.create(StockOutWordActivity.this, R.raw.beep);
            if (mp != null && mp.isPlaying()) {
                mp.stop();
                try {
                    mp.prepare();
                    mp.start();
                } catch(IOException e) {
                    e.printStackTrace();
                } catch (IllegalStateException e1) {
                    e1.printStackTrace();
                } catch (NullPointerException np) {
                    np.printStackTrace();
                }
            } else {
                try {
                    mp.start();
                } catch (IllegalStateException il) {
                    il.printStackTrace();
                } catch (NullPointerException n) {
                    n.printStackTrace();
                }
            }
            final Dialog dialog1 = new Dialog(this);
            dialog1.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog1.setContentView(R.layout.activity_dialog);
            dialog1.setCancelable(false);
            dialog1.setCanceledOnTouchOutside(false);
            dialog1.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            dialog1.show();
            TextView message     = dialog1.findViewById(R.id.message);
            Button ok            = dialog1.findViewById(R.id.ok);
            message.setText("Already scanned this item");
            ok.setOnClickListener(view -> {
                dialog1.dismiss();
                barcode.setFocusable(true);
                barcode.requestFocus();
                barcode.setText("");
                try {
                    if (mp != null && mp.isPlaying()) {
                        mp.stop();
                        mp.release();
                    }
                } catch (IllegalStateException ise) {
                    ise.printStackTrace();
                } catch (NullPointerException npe) {
                    npe.printStackTrace();
                }
            });
        });
    }

    @Override
    public void onBackPressed() {
       AlertDialog.Builder alert = new AlertDialog.Builder(this);
       alert.setTitle("Stock OutWord");
       alert.setMessage("Are you want to close app");
       alert.setPositiveButton("Ok", (dialogInterface, i) -> {
         super.onBackPressed();
       });
       alert.setNegativeButton("Cancel", (dialogInterface, i) -> {
       });
       alert.show();
    }

    public class Checked implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }
        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public void onTextChanged(CharSequence val, int i, int i1, int i2) {
            try {
                if (!TextUtils.isEmpty(barcode.getText().toString())) {
                    if (val.toString().length() > 0) {
                        if (val.toString().contains("\n")) {
                            if (Constants.isNetworkAvailable(StockOutWordActivity.this)) {
                                if(arrayList.size() > 0) {
                                    if(Constants.Existing(arrayList, barcode.getText().toString().replace("\n", ""))) {
                                        try {
                                            getNotification();
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                        return;
                                    }
                                }
                                if (state_Id != 0) {
                                    UploadBarcode(barcode.getText().toString().replace("\n", ""), qty.getText().toString(), location_Id);
                                    Constants.ProgressDialogShow(StockOutWordActivity.this);
                                    barcode.setText("");
                                } else {
                                    Constants.getToast(StockOutWordActivity.this, "Please Select StateId");
                                }
                            } else {
                                Constants.getToast(StockOutWordActivity.this, getResources().getString(R.string.connection));
                            }
                        }
                    }
                }
            } catch (NullPointerException jo) {
                jo.getMessage();
            }
        }
        @Override
        public void afterTextChanged(Editable editable) {
        }
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
            case R.id.Outword_box:
                if (arrayList.size() > 0) {
                    ArrayList<Plans> tempArrayList = new ArrayList<>();
                    Random r = new Random();
                    //int i1 = r.nextInt(10 - 0) + 1;
                    int i1 = (int) (Math.random() * (max - min + 1) + min);
                    for (int i = 0; i < arrayList.size(); i++) {
                        Plans plans = arrayList.get(i);
                        if (plans.getStatus()) {
                        } else {
                            plans.setStatus(true);
                            plans.setSetNumber(i1);
                            Log.e("Random Number :", String.valueOf(i1));
                            tempArrayList.add(plans);
                        }
                    }
                    planDetailsAdapter.notifyDataSetChanged();
                    if (hashMap.size() > 0) {
                        hashMap.put(hashMap.size(), tempArrayList);
                    } else {
                        hashMap.put(0, tempArrayList);
                    }
                }
                setUpdateUI();
                menu.findItem(R.id.Outword_box).setVisible(false);
                menu.findItem(R.id.Outword_tfs).setVisible(true);
                break;

            case R.id.Outword_tfs:
                if(Constants.isNetworkAvailable(StockOutWordActivity.this)) {
                    menu.findItem(R.id.Outword_box).setVisible(false);
                    menu.findItem(R.id.Outword_tfs).setVisible(false);
                    JSONObject json = new JSONObject();
                    try {
                        json.put("from_location", preferenceManager.getStoreId());
                        json.put("to_location",   String.valueOf(location_Id));
                        JSONArray jsonArray = new JSONArray();
                        for (Map.Entry<Integer, ArrayList<Plans>> item1 : hashMap.entrySet()) {
                            int key = item1.getKey();
                            ArrayList<Plans> value = item1.getValue();
                            JSONArray jsonArray1   = new JSONArray();
                            for (Plans plan : value) {
                                JSONObject jsonObject = new JSONObject();
                                try {
                                    jsonObject.put("barcode", plan.Barcode);
                                    jsonObject.put("quantity", "1.0");
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                jsonArray1.put(jsonObject);
                            }
                            jsonArray.put(jsonArray1);
                        }
                        json.put("boxes",             jsonArray);
                        json.put("stock_point_id",    Store_Point_Id);
                        json.put("return_to_vendor", false);
                        RequestBody body = RequestBody.create(JSON, json.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.StockTransfer)
                                .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(StockOutWordActivity.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("Upload Barcode", Response);
                                    Handler handler = new Handler(Looper.getMainLooper());
                                    handler.post(() -> {
                                        try {
                                            final JSONObject object1 = new JSONObject(Response);
                                            if (response.code() == 200) {
                                                if (object1.has(getResources().getString(R.string.success))) {
                                                    if (object1.getInt(getResources().getString(R.string.success)) == 1) {
                                                        menu.findItem(R.id.Outword_tfs).setVisible(false);
                                                        menu.findItem(R.id.Outword_box).setVisible(false);
                                                        barcode.requestFocus();
                                                        runOnUiThread(() -> {
                                                          try{
                                                             getShowDialog(object1.getString("msg"));
                                                          }catch(JSONException e) {
                                                            e.printStackTrace();
                                                          }
                                                        });
                                                        hashMap.clear();
                                                        arrayList.clear();
                                                        planDetailsAdapter.notifyDataSetChanged();
                                                        total_boxes.setText("Total Boxes : 0");
                                                        total_lines.setText("Total Lines : 0");
                                                        total_qty.setText(  "Total Qty : 0");
                                                    } else if (object1.getInt(getResources().getString(R.string.success)) == 3) {
                                                        runOnUiThread(() -> {
                                                            try {
                                                                Constants.getToast(StockOutWordActivity.this, object1.getString(getResources().getString(R.string.msg)));
                                                            } catch (JSONException e) {
                                                                e.printStackTrace();
                                                            }
                                                        });
                                                    } else {
                                                        Constants.getToast(StockOutWordActivity.this, object1.getString(getResources().getString(R.string.msg)));
                                                    }
                                                }
                                            }
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    });
                                } catch (NullPointerException io) {
                                    io.printStackTrace();
                                } finally {
                                    response.body().close();
                                }
                            }
                        });
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }else{
                   Constants.getToast(StockOutWordActivity.this,getResources().getString(R.string.connection));
                }
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    public void getShowDialog(String msg) {
        final Dialog dialog1 = new Dialog(this);
        dialog1.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog1.setContentView(R.layout.activity_dialog);
        dialog1.setCancelable(false);
        dialog1.setCanceledOnTouchOutside(false);
        dialog1.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        dialog1.show();
        TextView message = dialog1.findViewById(R.id.message);
        Button ok = dialog1.findViewById(R.id.ok);
        message.setText(msg);
        ok.setOnClickListener(view -> {
            dialog1.dismiss();
        });
    }

    public  void getCall() {
        final OkHttpClient client = new OkHttpClient();
        client.setConnectTimeout(240, TimeUnit.SECONDS);
        client.setReadTimeout(240, TimeUnit.SECONDS);
        client.setWriteTimeout(240, TimeUnit.SECONDS);
        Request request = new Request.Builder()
                .url(Constants.ToState)
                .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 com.squareup.okhttp.Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                Constants.ProgressDialogDismiss();
                if (e.getCause() != null && e.getCause() instanceof UnknownHostException) {
                } else {
                    runOnUiThread(() -> Constants.getToast(StockOutWordActivity.this, e.getMessage()));
                }
            }
            @Override
            public void onResponse(final com.squareup.okhttp.Response response) throws IOException {
                Constants.ProgressDialogDismiss();
                Response = response.body().string();
                try {
                    Handler handler = new Handler(Looper.getMainLooper());
                    handler.post(() -> {
                        if (response.code() == 200) {
                            try {
                                JSONObject obj = new JSONObject(Response);
                                if (obj.has(getResources().getString(R.string.success))) {
                                    stateArrayList.clear();
                                    State state = new State();
                                    state.setState_Id(0);
                                    state.setState_Name("Select");
                                    stateArrayList.add(state);
                                    if (obj.getInt(getResources().getString(R.string.success)) == 1) {
                                        Log.e("Response =====>", obj.toString());
                                        JSONArray jsonArray = obj.getJSONArray("data");
                                        for(int i = 0; i < jsonArray.length(); i++) {
                                           JSONObject jsonObject = jsonArray.getJSONObject(i);
                                           State state1 = new State();
                                           state1.setState_Id(jsonObject.getInt("state_id"));
                                           state1.setState_Name(jsonObject.getString("state_name"));
                                           stateArrayList.add(state1);
                                        }
                                        ArrayAdapter<State> stateArrayAdapter = new ArrayAdapter<>(StockOutWordActivity.this, android.R.layout.simple_list_item_1, stateArrayList);
                                        state_spinner.setAdapter(stateArrayAdapter);
                                    } else if (obj.getInt(getResources().getString(R.string.success)) == 3) {
                                        runOnUiThread(() -> {
                                            try{
                                               Login.logout(StockOutWordActivity.this);
                                               Constants.getToast(StockOutWordActivity.this, obj.getString("msg"));
                                            }catch(JSONException e) {
                                              e.printStackTrace();
                                            }
                                        });
                                    } else {
                                        runOnUiThread(() -> {
                                            try{
                                               Constants.getToast(StockOutWordActivity.this, obj.getString("msg"));
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                        });
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else {
                            runOnUiThread(() -> Constants.getToast(StockOutWordActivity.this, Response));
                        }
                    });
                } catch (NullPointerException io) {
                    io.printStackTrace();
                } finally {
                    response.body().close();
                }
            }
        });
    }

    public  void UploadBarcode(final String Barcode, final String qty, final int Id) {
        JSONObject object = new JSONObject();
        try{
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
               object.put(getResources().getString(R.string.barcode_upload),  Barcode);
               object.put(getResources().getString(R.string.quantity_upload), qty);
               object.put(getResources().getString(R.string.stock_point),     Store_Point_Id);
            }
        }catch(JSONException e){
          e.printStackTrace();
        }

        Log.e("Upload Barcode", 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.CheckBarcodeQty)
                .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(StockOutWordActivity.this, e.getMessage());
                   Constants.ProgressDialogDismiss();
                });
            }
            //9866272552
            @Override
            public void onResponse(final com.squareup.okhttp.Response response) throws IOException {
                try {
                    Constants.ProgressDialogDismiss();
                    final String Response = response.body().string();
                    Log.e("Upload Barcode", Response);
                    Handler handler = new Handler(Looper.getMainLooper());
                    handler.post(() -> {
                        try {
                            final JSONObject object1 = new JSONObject(Response);
                            if (response.code() == 200) {
                                if (object1.has(getResources().getString(R.string.success))) {
                                    if (object1.getInt(getResources().getString(R.string.success)) == 1) {
                                        menu.findItem(R.id.Outword_tfs).setVisible(false);
                                        menu.findItem(R.id.Outword_box).setVisible(true);
                                        barcode.requestFocus();
                                        Plans plans = new Plans();
                                        plans.setQty(qty);
                                        plans.setPlanId(Store_Point_Id);
                                        plans.setBarcode(Barcode);
                                        plans.setStatus(false);
                                        plans.setSetNumber(0);
                                        if (arrayList.size() > 0) {
                                            plans.setColumnId(arrayList.size() + 1);
                                        } else {
                                            plans.setColumnId(1);
                                        }
                                        arrayList.add(plans);
                                        setUpdateUI();
                                        Collections.sort(arrayList, Plans.getSortById());
                                        if (arrayList.size() > 0) {
                                            runOnUiThread(() -> {
                                                planDetailsAdapter = new PlanDetailsAdapter(StockOutWordActivity.this, arrayList);
                                                stockOutWord_recyclerView.setLayoutManager(new LinearLayoutManager(StockOutWordActivity.this));
                                                stockOutWord_recyclerView.setAdapter(planDetailsAdapter);
                                            });
                                        }
                                    } else if (object1.getInt(getResources().getString(R.string.success)) == 3) {
                                        runOnUiThread(() -> {
                                            try {
                                                Constants.getToast(StockOutWordActivity.this, object1.getString(getResources().getString(R.string.msg)));
                                                DoLogin();
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                        });
                                    } else {
                                        Constants.getToast(StockOutWordActivity.this, object1.getString(getResources().getString(R.string.msg)));
                                    }
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    });
                } catch (NullPointerException io) {
                    io.printStackTrace();
                } finally {
                    response.body().close();
                }
            }
        });
    }

    public void DoLogin() {
        dialog = new Dialog(StockOutWordActivity.this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.dialog_session);
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        dialog.show();
        final TextView userId = dialog.findViewById(R.id.relogin_userid);
        final TextView pass   = dialog.findViewById(R.id.relogin_pass);
        final Button reLogin  = dialog.findViewById(R.id.relogin_submit);
        userId.setText(preferenceManager.getUserId());
        reLogin.setOnClickListener(view -> {
            if (Constants.isNetworkAvailable(StockOutWordActivity.this)) {
                if (TextUtils.isEmpty(pass.getText().toString())) {
                    Constants.getToast(StockOutWordActivity.this, getResources().getString(R.string.enterPassword));
                } else {
                    doLogin(preferenceManager.getUserId(), Constants.getSHA256(pass.getText().toString()));
                    Constants.ProgressDialogShow(StockOutWordActivity.this);
                }
            } else {
                Constants.getToast(StockOutWordActivity.this, getResources().getString(R.string.connection));
            }
        });
    }

    public void doLogin(String userId, String pass) {
        JSONObject object = new JSONObject();
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                object.put(getResources().getString(R.string.empid),           userId);
                object.put(getResources().getString(R.string.password),        pass);
                object.put(getResources().getString(R.string.storeid),         preferenceManager.getStoreId());
                object.put(getResources().getString(R.string.dongle),     false);
                object.put(getResources().getString(R.string.android_version), Constants.VERSION);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody body          = RequestBody.create(JSON, object.toString());
        final OkHttpClient client = new OkHttpClient();
        client.setConnectTimeout(100, TimeUnit.SECONDS);
        client.setReadTimeout   (100,    TimeUnit.SECONDS);
        client.setWriteTimeout  (100,   TimeUnit.SECONDS);
        Request request           = new Request.Builder()
                .url(Constants.Login)
                .post(body)
                .addHeader(Constants.Type, Constants.App_json)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                if (e.getCause() != null && e.getCause() instanceof UnknownHostException) {
                } else {
                    Log.e("error ====>", e.getMessage());
                }
                Constants.ProgressDialogDismiss();
            }
            @Override
            public void onResponse(final com.squareup.okhttp.Response response) throws IOException {
                Constants.ProgressDialogDismiss();
                Response = response.body().string();
                try {
                    Handler handler = new Handler(Looper.getMainLooper());
                    handler.post(() -> {
                        if (response.code() == 200) {
                            try {
                                JSONObject obj          = new JSONObject(Response);
                                if (obj.has(getResources().getString(R.string.success))) {
                                    if (obj.getInt(getResources().getString(R.string.success)) == 1) {
                                        JSONObject data = obj.getJSONObject(getResources().getString(R.string.data));
                                        preferenceManager.setUserId(data.getString(getResources().getString(R.string.empid)));
                                        preferenceManager.setCustToken(data.getString(getResources().getString(R.string.usertoken)));
                                        preferenceManager.setStoreId(data.getString(getResources().getString(R.string.storeid)));
                                        preferenceManager.setPrefix(data.getString(getResources().getString(R.string.prefix)));
                                        preferenceManager.setLogged(true);
                                        dialog.dismiss();
                                    } else {
                                        Constants.getToast(StockOutWordActivity.this, obj.getString(getResources().getString(R.string.msg)));
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            } catch (NullPointerException np) {
                                np.printStackTrace();
                            }
                        } else {
                            Constants.getToast(StockOutWordActivity.this, Response);
                        }
                    });
                } catch (NullPointerException io) {
                    io.printStackTrace();
                } finally {
                    response.body().close();
                }
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    public void DeleteBarcode(final Plans plans1, final int position, ArrayList<Plans> plansArrayList) {
        int k = 0;
        for(int i = 0; i<arrayList.size(); i++){
            Plans plans  = arrayList.get(i);
            if (plans.getStatus()) {
                if( k > 1 ){
                  menu.findItem(R.id.Outword_tfs).setVisible(false);
                }else{
                  menu.findItem(R.id.Outword_tfs).setVisible(true);
                }
            } else {
                if( k > 0 ) {
                  menu.findItem(R.id.Outword_box).setVisible(true);
                }else {
                  menu.findItem(R.id.Outword_box).setVisible(false);
                }
                k++;
            }
        }
        arrayList.remove(position);
        planDetailsAdapter.notifyDataSetChanged();
        if (arrayList.size() > 0) {
            ArrayList<Integer> tempArrayList = new ArrayList<>();
            for (int i = 0; i < arrayList.size(); i++) {
                Plans plans = arrayList.get(i);
                if (plans.getStatus()) {
                } else {
                    tempArrayList.add(1);
                }
            }
            runOnUiThread(() -> {
                total_qty.setText("Total Qty :"     + arrayList.size());
                total_lines.setText("Total Lines :" + tempArrayList.size());
            });
            synchronized (hashMap) {
                try {
                    Iterator<Integer> it1 = hashMap.keySet().iterator();
                    while (it1.hasNext()) {
                        int key = it1.next();
                        ArrayList<Plans> value = hashMap.get(key);
                        if (value.size() == 1) {
                            Plans plans = value.get(0);
                            if (plans.getBarcode().equalsIgnoreCase(plans1.Barcode)) {
                                hashMap.remove(key);
                            }
                        } else if (value.size() > 1) {
                            for (Plans plan : value) {
                                if (plan.getBarcode().equalsIgnoreCase(plans1.Barcode)) {
                                    value.remove(plan);
                                }
                            }
                        }
                    }
                } catch (ConcurrentModificationException ce) {
                    ce.getMessage();
                }
            }
            runOnUiThread(() -> total_boxes.setText("Total Boxes :" + hashMap.size()));
        } else {
            runOnUiThread(() -> {
                total_qty.setText("Total Qty :  0");
                total_lines.setText("Total Lines : 0");
                total_boxes.setText("Total Boxes : 0");
                hashMap.clear();
                menu.findItem(R.id.Outword_box).setVisible(false);
                menu.findItem(R.id.Outword_tfs).setVisible(false);
            });
        }
        if (hashMap.size() > 0 && plansArrayList.size() > 0) {
            runOnUiThread(() -> total_boxes.setText("Total Boxes :" + hashMap.size()));
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu myMenu) {
        getMenuInflater().inflate(R.menu.menu_item, myMenu);
        this.menu = myMenu;
        menu.findItem(R.id.Outword_tfs).setVisible(false);
        menu.findItem(R.id.Outword_box).setVisible(false);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
        switch (adapterView.getId()) {
            case R.id.state_spinner:
                State state = stateArrayList.get(i);
                state_Id = stateArrayList.get(i).state_Id;
                Log.e("Id ====>", state.state_Name);
                if (!state.getState_Name().equalsIgnoreCase("Select")) {
                    getFormatAPI(state_Id);
                }
                break;

            case R.id.format_spinner:
                Format format = formatArrayList.get(i);
                format_Id = formatArrayList.get(i).pos_store_format_id;
                Log.e("Format ====>", String.valueOf(format.pos_store_format_id));
                if (!format.getStore_format().equalsIgnoreCase("Select")) {
                    getStateFormatAPI(state_Id, format_Id);
                }
                break;

            case R.id.location_spinner:
                StoreFormat storeFormat = storeFormatArrayList.get(i);
                if (!storeFormat.getStore_name().equalsIgnoreCase("Select")) {
                    location_Id = storeFormat.Id;
                    getStorePointId(preferenceManager.getStoreId());
                } else {
                    runOnUiThread(() -> {
                        Constants.getToast(StockOutWordActivity.this, "Please Select Location Name");
                    });
                }
                break;

            case R.id.uom:
                uomText = uom_spinner.getSelectedItem().toString();
                if (uomText.equalsIgnoreCase("units")) {
                    qty.setEnabled(false);
                    qty.setText("1");
                } else {
                    qty.setText("");
                    qty.setEnabled(true);
                }
                break;
        }
    }

    public void getStorePointId(String storeId) {
        final OkHttpClient client = new OkHttpClient();
        client.setConnectTimeout(240, TimeUnit.SECONDS);
        client.setReadTimeout(240, TimeUnit.SECONDS);
        client.setWriteTimeout(240, TimeUnit.SECONDS);
        Request request = new Request.Builder()
                .url      (Constants.StockPointId + storeId)
                .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 com.squareup.okhttp.Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                Constants.ProgressDialogDismiss();
                if (e.getCause() != null && e.getCause() instanceof UnknownHostException) {
                } else {
                    runOnUiThread(() -> Constants.getToast(StockOutWordActivity.this, e.getMessage()));
                }
            }
            @Override
            public void onResponse(final com.squareup.okhttp.Response response) throws IOException {
                Constants.ProgressDialogDismiss();
                Response = response.body().string();
                //Log.e("StateFormat =====>", Response);
                try {
                    Handler handler = new Handler(Looper.getMainLooper());
                    handler.post(() -> {
                        if (response.code() == 200) {
                            try {
                                JSONObject jsonObject = new JSONObject(Response);
                                if (jsonObject.has("data")) {
                                    Store_Point_Id = jsonObject.getString("data");
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else {
                            runOnUiThread(() -> Constants.getToast(StockOutWordActivity.this, Response));
                        }
                    });
                } catch (NullPointerException io) {
                    io.printStackTrace();
                } finally {
                    response.body().close();
                }
            }
        });
    }

    public void getStateFormatAPI(int state_id, int format_id) {
        final OkHttpClient client = new OkHttpClient();
        client.setConnectTimeout(240, TimeUnit.SECONDS);
        client.setReadTimeout(240, TimeUnit.SECONDS);
        client.setWriteTimeout(240, TimeUnit.SECONDS);
        Request request = new Request.Builder()
                .url(Constants.ToStoreFormat + state_id + "/" + format_id)
                .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 com.squareup.okhttp.Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                Constants.ProgressDialogDismiss();
                if(e.getCause() != null && e.getCause() instanceof UnknownHostException){
                }else{
                  runOnUiThread(() -> Constants.getToast(StockOutWordActivity.this, e.getMessage()));
                }
            }
            @Override
            public void onResponse(final com.squareup.okhttp.Response response) throws IOException {
                Constants.ProgressDialogDismiss();
                Response = response.body().string();
                try {
                    Handler handler = new Handler(Looper.getMainLooper());
                    handler.post(() -> {
                        if (response.code() == 200) {
                            try {
                                JSONObject obj = new JSONObject(Response);
                                if (obj.has(getResources().getString(R.string.success))) {
                                    storeFormatArrayList.clear();
                                    StoreFormat storeFormat = new StoreFormat();
                                    storeFormat.setId(0);
                                    storeFormat.setStore_name("Select");
                                    storeFormatArrayList.add(storeFormat);
                                    if (obj.getInt(getResources().getString(R.string.success)) == 1) {
                                        Log.e("Response =====>", obj.toString());
                                        JSONArray jsonArray = obj.getJSONArray("data");
                                        for (int i = 0; i < jsonArray.length(); i++) {
                                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                                            StoreFormat format1 = new StoreFormat();
                                            format1.setId(jsonObject.getInt("id"));
                                            format1.setStore_name(jsonObject.getString("store_name"));
                                            storeFormatArrayList.add(format1);
                                        }
                                        ArrayAdapter<StoreFormat> stateArrayAdapter = new ArrayAdapter<>(StockOutWordActivity.this, android.R.layout.simple_list_item_1, storeFormatArrayList);
                                        location_spinner.setAdapter(stateArrayAdapter);
                                    } else if (obj.getInt(getResources().getString(R.string.success)) == 3) {
                                        runOnUiThread(() -> {
                                            try {
                                                Login.logout(StockOutWordActivity.this);
                                                Constants.getToast(StockOutWordActivity.this, obj.getString("msg"));
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                        });
                                    } else {
                                        runOnUiThread(() -> {
                                            try {
                                                Constants.getToast(StockOutWordActivity.this, obj.getString("msg"));
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                        });
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else {
                            runOnUiThread(() -> Constants.getToast(StockOutWordActivity.this, Response));
                        }
                    });
                } catch (NullPointerException io) {
                    io.printStackTrace();
                } finally {
                    response.body().close();
                }
            }
        });
    }

    public void getFormatAPI(int state_id) {
        final OkHttpClient client = new OkHttpClient();
        client.setConnectTimeout(240, TimeUnit.SECONDS);
        client.setReadTimeout(240, TimeUnit.SECONDS);
        client.setWriteTimeout(240, TimeUnit.SECONDS);
        Request request = new Request.Builder()
                .url(Constants.ToFormat + state_id)
                .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 com.squareup.okhttp.Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                Constants.ProgressDialogDismiss();
                if (e.getCause() != null && e.getCause() instanceof UnknownHostException) {
                } else {
                   runOnUiThread(() -> Constants.getToast(StockOutWordActivity.this, e.getMessage()));
                }
            }
            @Override
            public void onResponse(final com.squareup.okhttp.Response response) throws IOException {
                Constants.ProgressDialogDismiss();
                Response = response.body().string();
                try {
                    Handler handler = new Handler(Looper.getMainLooper());
                    handler.post(() -> {
                        if (response.code() == 200) {
                            try {
                                JSONObject obj = new JSONObject(Response);
                                if (obj.has(getResources().getString(R.string.success))) {
                                    formatArrayList.clear();
                                    Format format = new Format();
                                    format.setPos_store_format_id(0);
                                    format.setStore_format("Select");
                                    formatArrayList.add(format);
                                    if (obj.getInt(getResources().getString(R.string.success)) == 1) {
                                        JSONArray jsonArray = obj.getJSONArray("data");
                                        for (int i = 0; i < jsonArray.length(); i++) {
                                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                                            Format format1 = new Format();
                                            format1.setPos_store_format_id(jsonObject.getInt("pos_store_format_id"));
                                            format1.setStore_format(jsonObject.getString("store_format"));
                                            formatArrayList.add(format1);
                                        }
                                        ArrayAdapter<Format> stateArrayAdapter = new ArrayAdapter<>(StockOutWordActivity.this, android.R.layout.simple_list_item_1, formatArrayList);
                                        format_spinner.setAdapter(stateArrayAdapter);
                                    } else if (obj.getInt(getResources().getString(R.string.success)) == 3) {
                                        runOnUiThread(() -> {
                                            try {
                                                Login.logout(StockOutWordActivity.this);
                                                Constants.getToast(StockOutWordActivity.this, obj.getString("msg"));
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                        });
                                    } else {
                                        runOnUiThread(() -> {
                                            try {
                                                Constants.getToast(StockOutWordActivity.this, obj.getString("msg"));
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                        });
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else {
                            runOnUiThread(() -> Constants.getToast(StockOutWordActivity.this, Response));
                        }
                    });
                } catch (NullPointerException io) {
                    io.printStackTrace();
                } finally {
                    response.body().close();
                }
            }
        });
    }

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

    public void setUpdateUI() {
        if (arrayList.size() > 0) {
            total_qty.setText("Total Qty :" + arrayList.size());
            ArrayList<Integer> tempArrayList = new ArrayList<>();
            for (int i = 0; i < arrayList.size(); i++) {
                Plans plans = arrayList.get(i);
                if (plans.getStatus()) {
                } else {
                   tempArrayList.add(1);
                }
            }
            total_lines.setText("Total Lines :" + tempArrayList.size());
        }
        if (hashMap.size() > 0) {
            total_boxes.setText("Total Boxes :" + hashMap.size());
        }
    }
}