package com.utopiaindustries.qualitychecker.ui.fragments;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.utopiaindustries.qualitychecker.R;
import com.utopiaindustries.qualitychecker.apiservice.ApiService;
import com.utopiaindustries.qualitychecker.apiservice.ApiServiceFactory;
import com.utopiaindustries.qualitychecker.db.DimensionRepository;
import com.utopiaindustries.qualitychecker.db.InspectionCheckpointSkuRepository;
import com.utopiaindustries.qualitychecker.db.InspectionLabelRepository;
import com.utopiaindustries.qualitychecker.db.ProductRepository;
import com.utopiaindustries.qualitychecker.db.ReportRepository;
import com.utopiaindustries.qualitychecker.models.InspectionCheckpointSku;
import com.utopiaindustries.qualitychecker.models.InspectionDimension;
import com.utopiaindustries.qualitychecker.models.InspectionLabel;
import com.utopiaindustries.qualitychecker.models.InspectionReport;
import com.utopiaindustries.qualitychecker.models.InspectionReportItem;
import com.utopiaindustries.qualitychecker.models.InspectionReportWrapper;
import com.utopiaindustries.qualitychecker.models.Product;
import com.utopiaindustries.qualitychecker.models.QualityLabel;
import com.utopiaindustries.qualitychecker.models.callback.SaveDraftReportCallback;
import com.utopiaindustries.qualitychecker.notification.NotificationHelper;
import com.utopiaindustries.qualitychecker.service.InspectionReportService;
import com.utopiaindustries.qualitychecker.store.Store;
import com.utopiaindustries.qualitychecker.ui.adapter.ItemHistoryAdapter;
import com.google.zxing.integration.android.IntentIntegrator;
import com.journeyapps.barcodescanner.CaptureActivity;
import com.utopiaindustries.qualitychecker.utils.FileUtils;

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class FirstStepFragment extends Fragment implements View.OnClickListener {

    private NavController navController;
    private Button leftFab, rightFab, showHistoryBtn, btnDraft;
    private EditText sku, boxCarton, itemPerBox, pieces, packagingDetails, boxCartonSelected, itemPerBoxSelected, piecesSelected, checkedBoxCartonSelected, checkedItemPerBoxSelected, checkedPiecesSelected;
    private Spinner markerplace, modelNumber, title, color, size, sp_inspectionLevel, sp_qLevelMajor, sp_qLevelMinor;
    private CheckBox fri, refri;
    private ImageButton searchSku, scanBtn;
    private TextView profileName;
    private ImageView profileImage;
    private ApiService apiService;
    private Store store;
    private InspectionReportService inspectionReportService;
    private EditText aqlSampleSize, cartonWeight, cartonLength, cartonWidth, cartonHeight;
    private EditText packWeight, packLength, packWidth, packHeight;
    TextView txtTesting;

    List<String> sizes = Collections.singletonList("[Size]");
    List<String> colors = Collections.singletonList("[Color]");
    List<String> titles = Collections.singletonList("[Title]");
    List<String> modelNumbers = Collections.singletonList("[Model Number]");
    List<String> marketplaces = Collections.singletonList("[ Marketplace ]");

    String inspectionLevel, qualityLevelMajor, qualityLevelMinor;

    String[] inspectionLevelArray = {"1", "2", "3"};
    String[] inspectionLevelQuality = {"1.0", "1.5", "2.5", "4.0"};

    boolean userSpInspection = false;
    boolean userSpMajor = false;
    boolean userSpMinor = false;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_first_step, container, false);
        //System.out.println("onCreateView---------->");
        SharedPreferences sharedPreferences = getContext().getSharedPreferences("login_prefs", Context.MODE_PRIVATE);
        long draftReportId = Long.parseLong(sharedPreferences.getString("draftReportId", null));
        //System.out.println("onCreateView---------->" + draftReportId);
        store = Store.getInstance();

        if (draftReportId > 0) {
            ReportRepository repository = new ReportRepository(getContext());

            InspectionReportWrapper report = repository.findDraftReportById(Long.parseLong(String.valueOf(draftReportId)));
            InspectionReport inspectionReport = getSingleReport(report);
            //System.out.println(inspectionReport);
            store.setReport(inspectionReport);
            //System.out.println("Report-SKU: " + store.getReport().getItems().get(0).getFnsku());
            inspectionLevel = String.valueOf(store.getReport().getItems().get(0).getInspectionLevel());
            qualityLevelMajor = String.valueOf(store.getReport().getItems().get(0).getMajorQualityLevel());
            qualityLevelMinor = String.valueOf(store.getReport().getItems().get(0).getMinorQualityLevel());

            String selectedString = store.getReport().getItems().get(0).getMarketplace();
            Log.e("marketPlace-draft: ",""+selectedString);

        }

        initializeViews(view);
        apiService = ApiServiceFactory.getApiService();
        inspectionReportService = InspectionReportService.getInstance();

        // set on click listener
        leftFab.setOnClickListener(this);
        rightFab.setOnClickListener(this);
        searchSku.setOnClickListener(this);
        btnDraft.setOnClickListener(this);
        scanBtn.setOnClickListener(this);
        showHistoryBtn.setOnClickListener(this);
        populateItem(store.getProducts(), true);
        prePopulateData(store.getProducts());
        updateProfileViews();
        //  sku.setText(store.getReport().getItems().get(0).getFnsku());

        if (draftReportId > 0) {

            if (sku.getText() != null) {
                populateProductDataOnSelection(sku.getText().toString(), "", true);
                store.setCheckpointSkus(new ArrayList<>());
                populateSkuCheckpointsParams(store.getReport().getItems().get(0).getSku(),
                        store.getReport().getItems().get(0).getMarketplace());
            }

            populateInspectionSpinners();
        }

        fri.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                store.getReport().setFri(true);
                refri.setChecked(false);
            } else {
                store.getReport().setFri(false);
                refri.setChecked(true);
            }
        });

        refri.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                store.getReport().setFri(false);
                fri.setChecked(false);
            } else {
                store.getReport().setFri(true);
                fri.setChecked(true);
            }
        });

        // marketplace
        markerplace.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (parent.getItemAtPosition(position) != null) {
                    String marketplaceOption = parent.getItemAtPosition(position).toString();
                    store.getReport().getItems().get(0).setMarketplace(marketplaceOption);
                    System.out.println(marketplaceOption);
                    populateProductDataOnSelection(
                            store.getReport().getItems().get(0).getFnsku(),
                            marketplaceOption,
                            false
                    );
                    populateSkuCheckpointsParams(
                            store.getReport().getItems().get(0).getSku(),
                            marketplaceOption
                    );
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                store.getReport().getItems().get(0).setMarketplace("");
            }
        });

        //Inspection Level
        sp_inspectionLevel.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (parent.getItemAtPosition(position) != null) {
                    inspectionLevel = parent.getItemAtPosition(position).toString();

                    store.getReport().getItems().get(0).setInspectionLevel((long) Double.parseDouble(inspectionLevel));

                    if (userSpInspection) {
                        checkedBoxCartonSelected.setText("");
                        checkedItemPerBoxSelected.setText("");
                        checkedPiecesSelected.setText("");
                        aqlSampleSize.setText("");
                    }
                    userSpInspection = true;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                store.getReport().getItems().get(0).setInspectionLevel(0);
            }
        });

        //Quality Level Major
        sp_qLevelMajor.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (parent.getItemAtPosition(position) != null) {
                    qualityLevelMajor = parent.getItemAtPosition(position).toString();

                    store.getReport().getItems().get(0).setMajorQualityLevel(Double.parseDouble(qualityLevelMajor));

                    if (userSpMajor) {
                        checkedBoxCartonSelected.setText("");
                        checkedItemPerBoxSelected.setText("");
                        checkedPiecesSelected.setText("");
                        aqlSampleSize.setText("");
                    }
                    userSpMajor = true;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                store.getReport().getItems().get(0).setMajorQualityLevel(0);
            }
        });

        //Quality Level Minor
        sp_qLevelMinor.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (parent.getItemAtPosition(position) != null) {
                    qualityLevelMinor = parent.getItemAtPosition(position).toString();

                    store.getReport().getItems().get(0).setMinorQualityLevel(Double.parseDouble(qualityLevelMinor));

                    if (userSpMinor) {
                        checkedBoxCartonSelected.setText("");
                        checkedItemPerBoxSelected.setText("");
                        checkedPiecesSelected.setText("");
                        aqlSampleSize.setText("");
                    }
                    userSpMinor = true;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                store.getReport().getItems().get(0).setMinorQualityLevel(0);
            }
        });

        // title
        title.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (parent.getItemAtPosition(position) != null) {
                    String titleOption = parent.getItemAtPosition(position).toString();
                    store.getReport().getItems().get(0).setTitle(titleOption);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                store.getReport().getItems().get(0).setTitle("");
            }
        });

        // model
        modelNumber.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (parent.getItemAtPosition(position) != null) {
                    String modelOption = parent.getItemAtPosition(position).toString();
                    store.getReport().getItems().get(0).setModelNumber(modelOption);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                store.getReport().getItems().get(0).setModelNumber("");
            }
        });

        // color
        color.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (parent.getItemAtPosition(position) != null) {
                    String colorOption = parent.getItemAtPosition(position).toString();
                    store.getReport().getItems().get(0).setSmColor(colorOption);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                store.getReport().getItems().get(0).setSmColor("");
            }
        });

        // size
        size.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (parent.getItemAtPosition(position) != null) {
                    String sizeOption = parent.getItemAtPosition(position).toString();
                    store.getReport().getItems().get(0).setSmSize(sizeOption);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                store.getReport().getItems().get(0).setSmSize("");
            }
        });

        //onTextChanges logic implementation
        //box = 1, itemPerBox, pieces // Item Selected Details
        boxCartonSelected.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                try {
                    int packsCount = 0, piecesCount = 0;
                    int boxCount = Integer.parseInt(s.toString());
                    if (itemPerBox.getText().toString().isEmpty() || pieces.getText().toString().isEmpty()) {
                        Toast.makeText(getContext(), "Enter Item/Pieces Per box", Toast.LENGTH_SHORT).show();
                    } else {
                        packsCount = (int) store.getProducts().get(0).getItemPerBox();
                        piecesCount = (int) store.getProducts().get(0).getItemPerPack();

                        int totalPacks = boxCount * packsCount;
                        int totalPieces = totalPacks * piecesCount;

                        //store.getReport().getItems().get(0).setPacksSelected(Long.parseLong(s.toString()));
                        if (store.isNewReportSelected()) {
                            //Log.e("Selected: ",""+store.isNewReportSelected());
                            //Log.e("bool-selected-1: ",""+store.isNewReportSelected());
                            //Log.e("bool-selected-2: ","true");
                            itemPerBoxSelected.setText(String.valueOf(totalPacks));
                            piecesSelected.setText(String.valueOf(totalPieces));
                        }
                        else {
                             //Log.e("bool-selected-3: ","false");
                            //Log.e("bool-selected-4: ","false"+String.valueOf(store.getReport().getItems().get(0).getPacksSelected()));
                            //Log.e("bool-selected-5: ","false"+String.valueOf(store.getReport().getItems().get(0).getPiecesSelected()));
                             itemPerBoxSelected.setText(String.valueOf(store.getReport().getItems().get(0).getPacksSelected()));
                             piecesSelected.setText(String.valueOf(store.getReport().getItems().get(0).getPiecesSelected()));
                        }
                    }

                    store.getReport().getItems().get(0).setCartonsSelected(Integer.parseInt(s.toString()));
                } catch (Exception e) {
                    e.printStackTrace();
                    store.getReport().getItems().get(0).setCartonsSelected(0);
                    store.setNewReportSelected(true);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        //checked Item
        checkedBoxCartonSelected.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                //Log.e("beforeTextChanged: ","***");
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //Log.e("onTextChanged: ","***");
                try {
                    int packsCount = 0, piecesCount = 0;
                    int boxCount = Integer.parseInt(s.toString());
                    if (itemPerBox.getText().toString().isEmpty() || pieces.getText().toString().isEmpty()) {
                        Toast.makeText(getContext(), "Enter Item/Pieces Per box", Toast.LENGTH_SHORT).show();
                    } else {
                        packsCount = (int) store.getProducts().get(0).getItemPerBox();
                        piecesCount = (int) store.getProducts().get(0).getItemPerPack();

                        int totalPacks = boxCount * packsCount;
                        int totalPieces = totalPacks * piecesCount;

                        if (store.isNewReportPresented()) {
                            //Log.e("bool-presented-1: ",""+store.isNewReportPresented());
                            //Log.e("bool-presented-2: ","true");
                            checkedItemPerBoxSelected.setText(String.valueOf(totalPacks));
                            checkedPiecesSelected.setText(String.valueOf(totalPieces));
                        }
                        else {
                            //Log.e("bool-presented-3: ","false");
                            checkedItemPerBoxSelected.setText(String.valueOf(store.getReport().getItems().get(0).getCheckedPacksSelected()));
                            checkedPiecesSelected.setText(String.valueOf(store.getReport().getItems().get(0).getCheckedPiecesSelected()));
                        }
                    }

                    store.getReport().getItems().get(0).setCheckedCartonsSelected(Integer.parseInt(s.toString()));
                } catch (Exception e) {
                    store.getReport().getItems().get(0).setCheckedCartonsSelected(0);
                    store.setNewReportPresented(true);
                    store.setNewReportSelected(true);
                    store.setNewAQL(true);

                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                //Log.e("afterTextChanged: ","***");
            }
        });

        itemPerBoxSelected.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                try {
                    //Log.e("bool-selected-onTextChanged: "," itemPerBoxSelected");
                    store.getReport().getItems().get(0).setPacksSelected(Integer.parseInt(s.toString()));
                } catch (Exception e) {
                    store.getReport().getItems().get(0).setPacksSelected(0);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        //checkedItemPerBox
        checkedItemPerBoxSelected.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                try {
                    //Log.e("bool-presented-onTextChanged: "," checkedItemPerBoxSelected");
                    store.getReport().getItems().get(0).setCheckedPacksSelected(Integer.parseInt(s.toString()));
                } catch (Exception e) {
                    store.getReport().getItems().get(0).setCheckedPacksSelected(0);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        piecesSelected.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                try {
                    //Log.e("bool-selected-onTextChanged: "," piecesSelected");
                    store.getReport().getItems().get(0).setPiecesSelected(Integer.parseInt(s.toString()));
                } catch (Exception e) {
                    store.getReport().getItems().get(0).setPiecesSelected(0);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        //checkedPieces
        checkedPiecesSelected.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                try {
                    //Log.e("bool-presented-onTextChanged: "," checkedPiecesSelected");
                    store.getReport().getItems().get(0).setCheckedPiecesSelected(Integer.parseInt(s.toString()));
                } catch (Exception e) {
                    store.getReport().getItems().get(0).setCheckedPiecesSelected(0);
                }

                try {
                    //calculate aql sample size
                    //Log.e("ItemPresentedDetails-pieces: ", "" + s.toString());
                    //Log.e("ItemPresentedDetails-inspectionLevel: ", "" + inspectionLevel);
                    if (!s.toString().isEmpty() && s.toString() != null) {
                        trackSampleCode(Integer.parseInt(s.toString()), (int) Double.parseDouble(inspectionLevel), Double.parseDouble(qualityLevelMajor), Double.parseDouble(qualityLevelMinor));
                    }
                    else {
                        aqlSampleSize.setText("");
                    }

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

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        //Carton Weight
        cartonWeight.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                try {
                    store.getReport().getItems().get(0).setCartonWeight(Float.parseFloat(s.toString()));
                } catch (Exception e) {
                    store.getReport().getItems().get(0).setCartonWeight(0);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        //Carton Length
        cartonLength.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                try {
                    store.getReport().getItems().get(0).setCartonLength(Float.parseFloat(s.toString()));
                } catch (Exception e) {
                    store.getReport().getItems().get(0).setCartonLength(0);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        //Carton Width
        cartonWidth.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                try {
                    store.getReport().getItems().get(0).setCartonWidth(Float.parseFloat(s.toString()));
                } catch (Exception e) {
                    store.getReport().getItems().get(0).setCartonWidth(0);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        //Carton Height
        cartonHeight.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                try {
                    store.getReport().getItems().get(0).setCartonHeight(Float.parseFloat(s.toString()));
                } catch (Exception e) {
                    store.getReport().getItems().get(0).setCartonHeight(0);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        //Pack Weight
        packWeight.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                try {
                    store.getReport().getItems().get(0).setPackWeight(Float.parseFloat(s.toString()));
                } catch (Exception e) {
                    store.getReport().getItems().get(0).setPackWeight(0);
            }}

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        //Pack Length
        packLength.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                try {
                    store.getReport().getItems().get(0).setPackLength(Float.parseFloat(s.toString()));
                } catch (Exception e) {
                    store.getReport().getItems().get(0).setPackLength(0);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        //Pack Width
        packWidth.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                try {
                    store.getReport().getItems().get(0).setPackWidth(Float.parseFloat(s.toString()));
                } catch (Exception e) {
                    store.getReport().getItems().get(0).setPackWidth(0);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        //Pack Height
        packHeight.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                try {
                    store.getReport().getItems().get(0).setPackHeight(Float.parseFloat(s.toString()));
                } catch (Exception e) {
                    store.getReport().getItems().get(0).setPackHeight(0);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        aqlSampleSize.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                try {
                    store.getReport().getItems().get(0).setSampleSize(Long.parseLong(s.toString()));

                    /*if (!s.toString().isEmpty() && s.toString() != null) {
                        trackSampleCodeWithSampleSize((int) Double.parseDouble(inspectionLevel), Double.parseDouble(qualityLevelMajor), Double.parseDouble(qualityLevelMinor),Integer.parseInt(s.toString()));
                    }*/
                } catch (Exception e) {
                    store.getReport().getItems().get(0).setSampleSize(0);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

//        generalRemarks.addTextChangedListener(new TextWatcher() {
//            @Override
//            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//
//            }
//
//            @Override
//            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                try {
//                    store.getReport().setGeneralRemarks( s.toString()  );
//                } catch ( Exception e ){
//                    store.getReport().setGeneralRemarks( "");
//                }
//            }
//
//            @Override
//            public void afterTextChanged(Editable s) {
//
//            }
//        });

        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        //System.out.println("onViewCreated---------->");
        store = Store.getInstance();
        //System.out.println("Draft Button Click-1" + store.getReport());
        //System.out.println("Report: " + store.getReport());
        //System.out.println("SKU: " + store.getReport().getItems().get(0).getFnsku());
    }

    @Override
    public void onClick(View v) {
        navController = Navigation.findNavController(requireView());
        if (v.getId() == R.id.button_draft_first) {

            store.setNewReportPresented(false);
            store.setNewReportSelected(false);
            store.setNewAQL(false);
            //--Draft Incomplete Report
            //Log.e("sku: ",""+sku.getText().toString());
            //Log.e("Market-place: ",""+store.getReport().getItems().get(0).getMarketplace());
            if (!sku.getText().toString().isEmpty() && !store.getReport().getItems().get(0).getMarketplace().equalsIgnoreCase("[ Marketplace ]")) {
                if (store.getReport() != null) {
                    inspectionReportService.saveDraftInLocalDb(getContext(), store.getReport(), new SaveDraftReportCallback() {
                        @Override
                        public void onSuccess() {
                            Handler handler = new Handler(Looper.getMainLooper());
                            handler.post(() -> {
                                // progressBar.setVisibility(View.INVISIBLE);
                                SharedPreferences sharedPreferences = getContext().getSharedPreferences("login_prefs", Context.MODE_PRIVATE);
                                SharedPreferences.Editor editor = sharedPreferences.edit();

                                editor.putString("draftReportId", "0");
                                editor.apply();

                                //Objects.requireNonNull(getActivity()).finish();
                                NotificationHelper.showNotification(Objects.requireNonNull(getContext()),
                                        "Utopia QA App",
                                        "Report is successfully drafted");

                                Toast.makeText(getContext(), "Report Saved as Draft", Toast.LENGTH_SHORT).show();

                            });
                        }

                        @Override
                        public void onFailure(Throwable throwable) {
                            Handler handler = new Handler(Looper.getMainLooper());
                            handler.post(() -> {
                                Toast.makeText(getContext(), throwable.getMessage(), Toast.LENGTH_LONG).show();
                                //progressBar.setVisibility(View.INVISIBLE);
                                NotificationHelper.showNotification(Objects.requireNonNull(getContext()),
                                        "Utopia QA App",
                                        "Error in saving report");
                            });
                        }
                    });
                }
            } else {
                Toast.makeText(getContext(), "Please enter or scan sku details", Toast.LENGTH_SHORT).show();
            }
            //---

        }
        if (v.getId() == R.id.button_left_frag_1) {
            if (getActivity() != null) {
                getActivity().finish();
            }
        }
        if (v.getId() == R.id.button_right_frag_1) {
            if (!sku.getText().toString().isEmpty() && !store.getReport().getItems().get(0).getMarketplace().equalsIgnoreCase("[ Marketplace ]")) {
                navController.navigate(R.id.action_firstStepFragment_to_secondStepFragment);
                store.setNewReportPresented(false);
                store.setNewReportSelected(false);
                store.setNewAQL(false);
            } else {
                Toast.makeText(getContext(), "Please enter or scan sku details", Toast.LENGTH_SHORT).show();
            }

        }
        if (v.getId() == R.id.search_sku_btn) {
            if (sku.getText() != null && !sku.getText().toString().isEmpty()) {
                populateProductDataOnSelection(sku.getText().toString(), "", true);
                store.setCheckpointSkus(new ArrayList<>());
                populateSkuCheckpointsParams(store.getReport().getItems().get(0).getSku(),
                        store.getReport().getItems().get(0).getMarketplace());
            }
        }
        if (v.getId() == R.id.scan_sku_btn) {
            IntentIntegrator integrator = new IntentIntegrator(getActivity());
            integrator.setCaptureActivity(CaptureActivity.class);
            integrator.setOrientationLocked(true);
            integrator.setBarcodeImageEnabled(true);
            integrator.initiateScan();
        }
        if (v.getId() == R.id.button_show_history) {
            openItemHistoryDialog();
        }
    }

    private void populateSkuCheckpointsParams(String sku, String marketplace) {
        if (sku != null && !sku.isEmpty() && marketplace != null && !marketplace.isEmpty()) {
            List<InspectionCheckpointSku> checkpointSkus = new InspectionCheckpointSkuRepository(getContext())
                    .findBySkuAndMarketplace(sku, marketplace);
            System.out.println(checkpointSkus);
            store.setCheckpointSkus(checkpointSkus);
        }
    }

    private void populateProductDataOnSelection(String fnsku, String marketplace, boolean populateMarketplace) {
        // setting the product details
        if (fnsku != null) {
            String fnskuStr = fnsku.trim();
            List<Product> products = new ProductRepository(getContext()).getProductBySkuOrAsin(fnskuStr, marketplace);
            System.out.println(products);
            Product product = products.stream().findFirst().orElse(new Product());
            store.getReport().getItems().get(0).setSku(product.getSku());
            store.getReport().getItems().get(0).setAsin(product.getAsin());
            store.getReport().getItems().get(0).setFnsku(fnskuStr);
            populateItem(products, populateMarketplace);
            store.setProducts(products);
            if (product.getCategory() != null) {
                List<InspectionDimension> dimensions = new DimensionRepository(getContext()).findByCategory(
                        product.getCategory()
                );
                store.setDimensionList(dimensions);
            }
        }
    }

    private void prePopulateData(List<Product> products) {
        //System.out.println("prePopulateData: " + store.getReport().getItems().get(0).getFnsku());
        fri.setChecked(store.getReport().getFri());
        refri.setChecked(!store.getReport().getFri());
        // sku
        sku.setText(store.getReport().getItems().get(0).getFnsku());
        System.out.println(products);
        System.out.println(store.getReport().getItems().get(0));

        if (!products.isEmpty()) {
            List<String> modelNumbers = products.stream().map(Product::getModelNumber).distinct().collect(Collectors.toList());

            String defaultModelSelection = store.getReport().getItems().get(0).getModelNumber();
            int defaultModelSelectionIndex = modelNumbers.indexOf(defaultModelSelection);
            modelNumber.setSelection(defaultModelSelectionIndex);
        }

        if (!products.isEmpty()) {
            List<String> titles = products.stream().map(Product::getTitle).distinct().collect(Collectors.toList());
            String defaultTitleSelection = store.getReport().getItems().get(0).getTitle();
            int defaultTitleSelectionIndex = titles.indexOf(defaultTitleSelection);
            title.setSelection(defaultTitleSelectionIndex);
        }

        populateInspectionSpinners();

    }

    private void populateInspectionSpinners() {
        String defaultInspectionSelection = String.valueOf(store.getReport().getItems().get(0).getInspectionLevel());
        int defaultInspectionSelectionIndex = java.util.Arrays.asList(inspectionLevelArray).indexOf(defaultInspectionSelection);
        sp_inspectionLevel.setSelection(defaultInspectionSelectionIndex);

        String defaultLevelMajorSelection = String.valueOf(store.getReport().getItems().get(0).getMajorQualityLevel());
        int defaultLevelMajorSelectionIndex = java.util.Arrays.asList(inspectionLevelQuality).indexOf(defaultLevelMajorSelection);
        sp_qLevelMajor.setSelection(defaultLevelMajorSelectionIndex);

        String defaultLevelMinorSelection = String.valueOf(store.getReport().getItems().get(0).getMinorQualityLevel());
        int defaultLevelMinorSelectionIndex = java.util.Arrays.asList(inspectionLevelQuality).indexOf(defaultLevelMinorSelection);
        sp_qLevelMinor.setSelection(defaultLevelMinorSelectionIndex);

        String selectedString = store.getReport().getItems().get(0).getMarketplace();
        //Log.e("marketPlace-draft-selected: ",""+selectedString);
        int index = marketplaces.indexOf(selectedString);
        //Log.e("marketPlace-draft-index: ",""+index);
        markerplace.setSelection(index);

    }

    private void populateItem(List<Product> products, boolean populateMarketplace) {
        if (populateMarketplace) {
            populateMarketplaces(products);
            System.out.println("in");
        }
        populateModelNumber(products);
        populateTitle(products);
        populateColor(products);
        populateSize(products);
        populateItemPresentedDetails(products);
    }

    private void populateItemPresentedDetails(List<Product> products) {
        try {
            if (!products.isEmpty()) {
                Product product = products.get(0);
                String inventory = String.valueOf(product.getInventory());
                String itemPerBoxText = String.valueOf(product.getInventory() * product.getItemPerPack());
                String boxCartonText = String.valueOf((product.getInventory() / product.getItemPerBox()));

                @SuppressLint("DefaultLocale") String packagingDetailsText = String.format("%d Item per Pack, %d Pack per Box", product.getItemPerPack(), product.getItemPerBox());
                itemPerBox.setText(inventory);
                pieces.setText(itemPerBoxText);
                boxCarton.setText(boxCartonText);
                packagingDetails.setText(packagingDetailsText);

                //Log.e("Carton: ",""+String.valueOf(store.getReport().getItems().get(0).getCartonsSelected()));

                boxCartonSelected.setText(store.getReport().getItems().get(0).getCartonsSelected() != 0
                        ? String.valueOf(store.getReport().getItems().get(0).getCartonsSelected()) : "");

                //itemPerBoxSelected.setText(String.valueOf(store.getReport().getItems().get(0).getPacksSelected()));
                //piecesSelected.setText(String.valueOf(store.getReport().getItems().get(0).getPiecesSelected()));

                checkedBoxCartonSelected.setText(store.getReport().getItems().get(0).getCheckedCartonsSelected() != 0
                        ? String.valueOf(store.getReport().getItems().get(0).getCheckedCartonsSelected()) : "");

                //checkedItemPerBoxSelected.setText(String.valueOf(store.getReport().getItems().get(0).getCheckedPacksSelected()));
                //checkedPiecesSelected.setText(String.valueOf(store.getReport().getItems().get(0).getCheckedPiecesSelected()));

                cartonWeight.setText(store.getReport().getItems().get(0).getCartonWeight() != 0.0f
                        ? String.valueOf(store.getReport().getItems().get(0).getCartonWeight()) : "");
                cartonLength.setText(store.getReport().getItems().get(0).getCartonLength() != 0.0f
                        ? String.valueOf(store.getReport().getItems().get(0).getCartonLength()) : "");
                cartonWidth.setText(store.getReport().getItems().get(0).getCartonWidth() != 0.0f
                        ? String.valueOf(store.getReport().getItems().get(0).getCartonWidth()) : "");
                cartonHeight.setText(store.getReport().getItems().get(0).getCartonHeight() != 0.0f
                        ? String.valueOf(store.getReport().getItems().get(0).getCartonHeight()) : "");

                packWeight.setText(store.getReport().getItems().get(0).getPackWeight() != 0.0f
                        ? String.valueOf(store.getReport().getItems().get(0).getPackWeight()) : "");
                packLength.setText(store.getReport().getItems().get(0).getPackLength() != 0.0f
                        ? String.valueOf(store.getReport().getItems().get(0).getPackLength()) : "");
                packWidth.setText(store.getReport().getItems().get(0).getPackWidth() != 0.0f
                        ? String.valueOf(store.getReport().getItems().get(0).getPackWidth()) : "");
                packHeight.setText(store.getReport().getItems().get(0).getPackHeight() != 0.0f
                        ? String.valueOf(store.getReport().getItems().get(0).getPackHeight()) : "");


                aqlSampleSize.setText(String.valueOf(store.getReport().getItems().get(0).getSampleSize()));

                //   generalRemarks.setText( store.getReport().getItems().get(0).getSampleSize() );

                store.getReport().getItems().get(0).setTotalPresentPieces(Long.parseLong(inventory));
                store.getReport().getItems().get(0).setTotalPresentPacks(Long.parseLong(itemPerBoxText));
                store.getReport().getItems().get(0).setTotalPresentCartons(Long.parseLong(boxCartonText));
                store.getReport().getItems().get(0).setPackingDetails(packagingDetailsText);

            }
        } catch (Exception e) {
            itemPerBox.setText("0");
            pieces.setText("0");
            boxCarton.setText("0");
            packagingDetails.setText("");
        }
    }


    private void populateSize(List<Product> products) {

        if (!products.isEmpty()) {
            sizes = products.stream().map(Product::getSmSize).distinct().filter(Objects::nonNull).collect(Collectors.toList());
        }
        if (!sizes.isEmpty()) {
            ArrayAdapter<String> adapter = new ArrayAdapter<>(Objects.requireNonNull(getContext()),
                    android.R.layout.simple_spinner_dropdown_item, sizes.toArray(new String[0]));
            size.setAdapter(adapter);
            //
            String sizeOption = (String) size.getSelectedItem();
            store.getReport().getItems().get(0).setSmSize(sizeOption);
        }
    }

    private void populateColor(List<Product> products) {

        if (!products.isEmpty()) {
            colors = products.stream().map(Product::getSmColor).distinct().filter(Objects::nonNull).collect(Collectors.toList());
        }
        if (!colors.isEmpty()) {

            ArrayAdapter<String> adapter = new ArrayAdapter<>(Objects.requireNonNull(getContext()),
                    android.R.layout.simple_spinner_dropdown_item, colors.toArray(new String[0]));
            color.setAdapter(adapter);
            String colorOption = (String) color.getSelectedItem();
            store.getReport().getItems().get(0).setSmColor(colorOption);
        }
    }

    private void populateTitle(List<Product> products) {

        if (!products.isEmpty()) {
            titles = products.stream().map(Product::getTitle).distinct().filter(Objects::nonNull).collect(Collectors.toList());
        }
        if (!titles.isEmpty()) {
            ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item, titles.toArray(new String[0]));
            title.setAdapter(adapter);
            String titleOption = (String) title.getSelectedItem();
            store.getReport().getItems().get(0).setTitle(titleOption);
        }
    }


    private void populateModelNumber(List<Product> products) {

        if (!products.isEmpty()) {
            modelNumbers = products.stream().map(Product::getModelNumber).distinct().filter(Objects::nonNull).collect(Collectors.toList());
        }
        if (!modelNumbers.isEmpty()) {
            ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item, modelNumbers.toArray(new String[0]));
            modelNumber.setAdapter(adapter);

            String modelOption = (String) modelNumber.getSelectedItem();
            store.getReport().getItems().get(0).setModelNumber(modelOption);
        }
    }

    private void populateMarketplaces(List<Product> products) {

        if (!products.isEmpty()) {
            marketplaces = products.stream().map(Product::getMarketplace).distinct().filter(Objects::nonNull).collect(Collectors.toList());
        }
        if (!marketplaces.isEmpty()) {
            ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item, marketplaces.toArray(new String[0]));
            markerplace.setAdapter(adapter);
            //
            String marketplaceOption = (String) markerplace.getSelectedItem();
            //.getReport().getItems().get(0).setMarketplace(marketplaceOption);
        }

//if (store.getReport().getItems().get(0).getInspectionLevel() == 0) {
            ArrayAdapter<String> adapterInspectionLevel = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item, inspectionLevelArray);
            sp_inspectionLevel.setAdapter(adapterInspectionLevel);
      //  }

      //  if (store.getReport().getItems().get(0).getMajorQualityLevel() == 0) {
            ArrayAdapter<String> adapterLevelMajor = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item, inspectionLevelQuality);
            sp_qLevelMajor.setAdapter(adapterLevelMajor);
      //  }

      //  if (store.getReport().getItems().get(0).getMinorQualityLevel() == 0) {
            ArrayAdapter<String> adapterLevelMinor = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item, inspectionLevelQuality);
            sp_qLevelMinor.setAdapter(adapterLevelMinor);
      //  }

    }


    /*
     *  initialize views
     * */
    private void initializeViews(View view) {
        leftFab = view.findViewById(R.id.button_left_frag_1);
        rightFab = view.findViewById(R.id.button_right_frag_1);
        btnDraft = view.findViewById(R.id.button_draft_first);
        markerplace = view.findViewById(R.id.marketplace);
        sp_inspectionLevel = view.findViewById(R.id.sp_inspectionLevel);
        sp_qLevelMajor = view.findViewById(R.id.sp_qLevelMajor);
        sp_qLevelMinor = view.findViewById(R.id.sp_qLevelMinor);
        sku = view.findViewById(R.id.sku);
        modelNumber = view.findViewById(R.id.model_number);
        title = view.findViewById(R.id.title);
        color = view.findViewById(R.id.color);
        size = view.findViewById(R.id.size);
        boxCarton = view.findViewById(R.id.box_carton);
        itemPerBox = view.findViewById(R.id.item_per_box);
        pieces = view.findViewById(R.id.pieces);
        packagingDetails = view.findViewById(R.id.packaging);
        boxCartonSelected = view.findViewById(R.id.box_carton_selected);
        itemPerBoxSelected = view.findViewById(R.id.item_per_box_selected);
        piecesSelected = view.findViewById(R.id.pieces_selected);
        txtTesting = view.findViewById(R.id.txtTesting);

        aqlSampleSize = view.findViewById(R.id.et_aql_sample_size);

        cartonWeight = view.findViewById(R.id.et_carton_weight);
        cartonLength = view.findViewById(R.id.et_carton_length);
        cartonWidth = view.findViewById(R.id.et_carton_width);
        cartonHeight = view.findViewById(R.id.et_carton_height);

        packWeight = view.findViewById(R.id.et_pack_weight);
        packLength = view.findViewById(R.id.et_pack_length);
        packWidth = view.findViewById(R.id.et_pack_width);
        packHeight = view.findViewById(R.id.et_pack_height);

        checkedBoxCartonSelected = view.findViewById(R.id.checked_box_carton_selected);
        checkedItemPerBoxSelected = view.findViewById(R.id.checked_item_per_box_selected);
        checkedPiecesSelected = view.findViewById(R.id.checked_pieces_selected);

        fri = view.findViewById(R.id.fri);
        refri = view.findViewById(R.id.refri);
        searchSku = view.findViewById(R.id.search_sku_btn);
        profileName = view.findViewById(R.id.first_step_name);
        profileImage = view.findViewById(R.id.first_step_profile_image);
        scanBtn = view.findViewById(R.id.scan_sku_btn);
        showHistoryBtn = view.findViewById(R.id.button_show_history);
    }

    public void onBarcodeScanResult(String result) {
        if (result != null && !result.isEmpty()) {
            store.getReport().getItems().get(0).setSku(result);
            System.out.println("SKU-2: " + store.getReport().getItems().get(0).getFnsku());
            sku.setText(result);
        }
    }

    private void openItemHistoryDialog() {
        LayoutInflater inflater = LayoutInflater.from(getContext());
        View dialogView = inflater.inflate(R.layout.item_history, null);
        // recycler view
        RecyclerView itemHistoryRecyclerView = dialogView.findViewById(R.id.item_history_recyclerview);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        itemHistoryRecyclerView.setLayoutManager(layoutManager);
        AlertDialog.Builder builder = new AlertDialog.Builder(Objects.requireNonNull(getContext()));

        // set adapter
        ItemHistoryAdapter itemHistoryAdapter = new ItemHistoryAdapter(new ArrayList<>());
        itemHistoryRecyclerView.setAdapter(itemHistoryAdapter);

        builder.setView(dialogView)
                .setTitle("Item History")
                .setPositiveButton("OK", (dialog, which) -> {
                    dialog.dismiss();
                })
                .setNegativeButton("Cancel", (dialog, which) -> {
                    // Handle Cancel button click
                    dialog.dismiss();
                });
        if (store.getReport().getItems().get(0).getSku() != null) {
            apiService.fetchItemsLogs(store.getReport().getItems().get(0).getSku()).enqueue(
                    new Callback<List<InspectionReportItem>>() {
                        @SuppressLint("NotifyDataSetChanged")
                        @Override
                        public void onResponse(Call<List<InspectionReportItem>> call, Response<List<InspectionReportItem>> response) {
                            if (response.isSuccessful() && response.body() != null) {
                                // set adapter
                                System.out.println(response.body());
                                ItemHistoryAdapter itemHistoryAdapter = new ItemHistoryAdapter(response.body());
                                itemHistoryRecyclerView.setAdapter(itemHistoryAdapter);
                                itemHistoryAdapter.notifyDataSetChanged();
                            }
                        }

                        @Override
                        public void onFailure(Call<List<InspectionReportItem>> call, Throwable t) {
                            System.out.println(t.getMessage());
                        }
                    }
            );
        }
        // Show the dialog
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    private void updateProfileViews() throws NullPointerException {
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("login_prefs", Context.MODE_PRIVATE);
        profileName.setText(sharedPreferences.getString("name", null));
        Glide.with(getContext())
                .load(store.getProfileImage())
                .into(profileImage);
    }

    private InspectionReport getSingleReport(InspectionReportWrapper wrapper) {
        InspectionReport report = null;

        if (wrapper != null) {
            try {
                // Get byte array from file content path
                byte[] result = FileUtils.readFile(wrapper.getContent());

                // Convert byte array to an InspectionReport object
                ByteArrayInputStream byteIn = new ByteArrayInputStream(result);
                ObjectInputStream in = new ObjectInputStream(byteIn);
                report = (InspectionReport) in.readObject();

                // Set additional details from the wrapper
                report.setWrapperId(wrapper.getId());
                report.setFilePath(wrapper.getContent());

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

        return report;
    }

    private void trackSampleCode(int itemPresentedPieces, int inspectionLevel, double selectedLevelMajor, double selectedLevelMinor) {
        try {
            String sampleCode = "";
            double levelMajor = 0.0, levelMinor = 0.0;
            int sampleSizeMajor = 0;
            int sampleSizeMinor = 0;
            List<InspectionLabel> inspectionGeneralLabels = new InspectionLabelRepository(getContext()).getInspectionLabels();
            List<QualityLabel> inspectionAcceptableQualities = new InspectionLabelRepository(getContext()).getQualityLabels();

            //for sample code
            for (InspectionLabel label : inspectionGeneralLabels) {
                if (label.getInspectionLevel() == inspectionLevel &&
                        label.getMinLotSize() <= itemPresentedPieces &&
                        label.getMaxLotSize() >= itemPresentedPieces) {
                    sampleCode = label.getSampleCode();
                    //Log.e("sampleCode: ",""+sampleCode);
                    break;
                }
            }

            //For level major
            for (QualityLabel quality : inspectionAcceptableQualities) {
                if (quality.getQualityLevel() == selectedLevelMajor && Objects.equals(quality.getSampleCode(), sampleCode)) {
                    levelMajor = quality.getNoOfAcceptedDefects();
                    sampleSizeMajor = quality.getSampleSize();
                }

                //For Level Minor
                if (quality.getQualityLevel() == selectedLevelMinor &&
                        Objects.equals(quality.getSampleCode(), sampleCode)) {
                    levelMinor = quality.getNoOfAcceptedDefects();
                    sampleSizeMinor = quality.getSampleSize();
                }
            }

            /*String testDetails = "Item Presented Pieces: " + itemPresentedPieces
                    + "\nInspection Level: " + inspectionLevel
                    + "\nSelected Level Major: " + selectedLevelMajor
                    + "\nSelected Level Minor: " + selectedLevelMinor
                    + "\nSample Code: " + sampleCode
                    + "\nLevel Major Defects: " + levelMajor
                    + "\nLevel Minor Defects: " + levelMinor
                    + "\nSampleSizeMajor: " + sampleSizeMajor
                    + "\nSampleSizeMinor: " + sampleSizeMinor;*/

            //txtTesting.setText(testDetails);
            //Log.e("SampleSizeMajor: ",""+sampleSizeMajor);

            Log.e("New-selected",""+store.isNewReportSelected());
            Log.e("New-AQL",""+store.isNewAQL());
            if (store.isNewAQL()) {

                aqlSampleSize.setText(String.valueOf(sampleSizeMajor));

                store.getReport().getItems().get(0).setSampleSize(sampleSizeMajor);
                store.getReport().getItems().get(0).setLevelMajorDefects((int) levelMajor);
                store.getReport().getItems().get(0).setLevelMinorDefects((int) levelMinor);

                Log.e("New-Level-Major: ",""+levelMajor);
                Log.e("New-Level-Minor: ",""+levelMinor);
            }
            else {
                aqlSampleSize.setText(String.valueOf(store.getReport().getItems().get(0).getSampleSize()));
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }


            /*if (minorInspectionAcceptableQuality != null && majorInspectionAcceptableQuality != null) {
                minorAcceptedCriteriaFromAqlMap.put(item.getId(), minorInspectionAcceptableQuality.getNoOfAcceptedDefects());
                majorAcceptedCriteriaFromAqlMap.put(item.getId(), majorInspectionAcceptableQuality.getNoOfAcceptedDefects());
            }*/

    }

    private void trackSampleCodeWithSampleSize(int inspectionLevel, double selectedLevelMajor, double selectedLevelMinor, int aqlSampleSizeValue) {
        try {
            String sampleCode = "";
            double levelMajor = 0.0, levelMinor = 0.0;
            int sampleSizeMajor = 0;
            int sampleSizeMinor = 0;

            List<InspectionLabel> inspectionGeneralLabels = new InspectionLabelRepository(getContext()).getInspectionLabels();
            List<QualityLabel> inspectionAcceptableQualities = new InspectionLabelRepository(getContext()).getQualityLabels();

            // Now determine the sample code based on aqlSampleSizeValue
            outerLoop:
            for (InspectionLabel label : inspectionGeneralLabels) {
                if (label.getInspectionLevel() == inspectionLevel) {
                    // Look for the QualityLabel that matches the desired sample size and sample code
                    for (QualityLabel quality : inspectionAcceptableQualities) {
                        if (Objects.equals(quality.getSampleCode(), label.getSampleCode()) &&
                                quality.getSampleSize() == aqlSampleSizeValue) {
                            sampleCode = label.getSampleCode();
                            break outerLoop;
                        }
                    }
                }
            }

            // For level major and minor
            for (QualityLabel quality : inspectionAcceptableQualities) {
                if (Objects.equals(quality.getSampleCode(), sampleCode)) {
                    if (quality.getQualityLevel() == selectedLevelMajor) {
                        levelMajor = quality.getNoOfAcceptedDefects();
                        sampleSizeMajor = quality.getSampleSize();
                    }

                    if (quality.getQualityLevel() == selectedLevelMinor) {
                        levelMinor = quality.getNoOfAcceptedDefects();
                        sampleSizeMinor = quality.getSampleSize();
                    }
                }
            }

            //store.getReport().getItems().get(0).setSampleSize(sampleSizeMajor);
            store.getReport().getItems().get(0).setLevelMajorDefects((int) levelMajor);
            store.getReport().getItems().get(0).setLevelMinorDefects((int) levelMinor);

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


    /*@Override
    public void onResume() {
        super.onResume();

        userSpInspection = true;
        userSpMajor = true;
        userSpMinor = true;
    }*/
}
