package com.example.java.sample;

import static androidx.activity.result.contract.ActivityResultContracts.*;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;

import androidx.activity.result.ActivityResultLauncher;
import androidx.annotation.NonNull;
import androidx.core.content.PermissionChecker;
import androidx.core.view.MenuProvider;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentResultListener;
import androidx.lifecycle.Lifecycle;
import androidx.navigation.fragment.NavHostFragment;

import com.example.java.sample.databinding.FragmentMainBinding;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResponse;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.location.SettingsClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.seikoinstruments.sdk.thermalprinter.BarcodeScannerListener;
import com.seikoinstruments.sdk.thermalprinter.CallbackFunctionListener;
import com.seikoinstruments.sdk.thermalprinter.PrinterManager;

import java.io.UnsupportedEncodingException;
import java.util.Objects;

public class MainFragment extends Fragment implements CallbackFunctionListener, BarcodeScannerListener {
    public static final int REQUEST_LOCATION_SETTING_RESOLUTION = 1004;
    private Handler mHandler = null;
    private Function mSdkFunction = null;
    private IndicatorDialogFragment mIndicatorDialog = null;
    private boolean isRunning = false;
    private String mLanguage = "en";

    // This property is only valid between onCreateView and onDestroyView.
    private FragmentMainBinding binding;

    // Define the behavior when a button on the toolbar is pressed.
    private MenuProvider menuProvider = new MenuProvider() {
        @Override
        public void onCreateMenu(@NonNull Menu menu, @NonNull MenuInflater menuInflater) {
            menuInflater.inflate(R.menu.tool_bar_menu, menu);
        }

        @Override
        public boolean onMenuItemSelected(@NonNull MenuItem item) {
            // Handle item selection.
            if (item.getItemId() == R.id.menu_setting) {
                requireActivity().removeMenuProvider(menuProvider);
                showSettingFragment();
                return true;
            }
            return false;
        }
    };

    @Override
    public View onCreateView(
            @NonNull LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState
    ) {
        // Initialize handler, inflate the binding layout, and return the root view
        if(mHandler == null) {
            mHandler = new Handler(Looper.getMainLooper());
        }
        if(binding == null) {
            binding = FragmentMainBinding.inflate(inflater, container, false);
        }
        return binding.getRoot();
    }

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

        // Get device language settings
        Configuration config = getResources().getConfiguration();
        mLanguage = config.getLocales().get(0) .getLanguage() ;

        String[] mPrinterTypeValues = getResources().getStringArray(R.array.printer_type_values_list);
        String[] mPrinterModelValues = getResources().getStringArray(R.array.printer_model_values_list);

        if(mSdkFunction == null) {
            mSdkFunction = new Function(requireActivity().getApplicationContext(), mLanguage);
        }

        if(!isAdded() ){
            return;
        }

        // Set up fragment result listener
        getParentFragmentManager().setFragmentResultListener(MainActivity.REQUEST_KEY_SEARCH, this, new FragmentResultListener() {
            @Override
            public void onFragmentResult(@NonNull String requestKey, @NonNull Bundle bundle) {
                binding.editTextAddress.setText(bundle.getString("key_address"));
            }
        });
        getParentFragmentManager().setFragmentResultListener(MainActivity.REQUEST_KEY_SETTINGS, this, new FragmentResultListener() {
            @Override
            public void onFragmentResult(@NonNull String requestKey, @NonNull Bundle bundle) {
                if(mSdkFunction != null) {
                    mSdkFunction.applySettings(
                            bundle.getInt(MainActivity.BUNDLE_KEY_SOCKET_KEEPING_TIME),
                            bundle.getInt(MainActivity.BUNDLE_KEY_SEND_TIMEOUT),
                            bundle.getInt(MainActivity.BUNDLE_KEY_RECEIVE_TIMEOUT),
                            bundle.getInt(MainActivity.BUNDLE_KEY_CODE_PAGE),
                            bundle.getInt(MainActivity.BUNDLE_KEY_INTERNATION_CHAR),
                            bundle.getInt(MainActivity.BUNDLE_KEY_SECURE_CONNECTION)
                    );
                }
            }
        });

        // Initialize UI components
        initializeUI();
        binding.textViewSdkVersion.setText("SDK Version: "+ mSdkFunction.getSdkVersion());

        // Set up adapters for spinners
        ArrayAdapter<String> printerTypeAdapter = new ArrayAdapter<>(requireContext(), android.R.layout.simple_spinner_dropdown_item, getResources().getStringArray(R.array.printer_type_list));
        binding.spinnerPrintType.setAdapter(printerTypeAdapter);
        ArrayAdapter<String> printerModelAdapter = new ArrayAdapter<>(requireContext(), android.R.layout.simple_spinner_dropdown_item, getResources().getStringArray(R.array.printer_model_list));
        binding.spinnerPrintModel.setAdapter(printerModelAdapter);

        // Set up click listeners for buttons
        binding.buttonSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isRunning()) {
                    setRunningState(true) ;
                    // Handle search button click
                    // Get printer type (interface)
                    int printerType = binding.spinnerPrintType.getSelectedItemPosition();
                    MainActivity mainActivity = (MainActivity) requireActivity();
                    mainActivity.mPrinterType = printerType;

                    if (printerType == PrinterManager.PRINTER_TYPE_BLUETOOTH) {
                        if (PermissionChecker.checkSelfPermission(requireActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PermissionChecker.PERMISSION_GRANTED) {
                            // Request location permission if not granted
                            fragmentResultLauncher_permissionRequest.launch(android.Manifest.permission.ACCESS_FINE_LOCATION);
                            setRunningState(false) ;
                            return;
                        }
                        // For Android 12 or higher
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                            if ((PermissionChecker.checkSelfPermission(requireActivity(), android.Manifest.permission.BLUETOOTH_CONNECT) != PermissionChecker.PERMISSION_GRANTED)
                                    || (PermissionChecker.checkSelfPermission(requireActivity(), android.Manifest.permission.BLUETOOTH_SCAN) != PermissionChecker.PERMISSION_GRANTED)) {
                                // Request Bluetooth permissions for Android 12 and above
                                fragResultLauncher_PermsAndroid12.launch(new String[]{android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_SCAN});
                                setRunningState(false) ;
                                return;
                            }
                        }
                        // For Android 10 or higher
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                            // Check location request
                            checkLocationRequest();
                            setRunningState(false) ;
                            return;
                        }
                    }

                    // Navigate to DeviceFragment
                    NavHostFragment.findNavController(MainFragment.this)
                            .navigate(R.id.action_MainFragment_to_DeviceFragment);
                    setRunningState(false) ;
                }
            }
        });

        binding.buttonConnect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isRunning()) {
                    setRunningState(true) ;
                    showIndicatorDialog();
                    // Handle connect button click
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            // Perform connection
                            String finalResultMessage = mSdkFunction.connectSample(
                                    Integer.parseInt(mPrinterTypeValues[binding.spinnerPrintType.getSelectedItemPosition()]),
                                    Integer.parseInt(mPrinterModelValues[binding.spinnerPrintModel.getSelectedItemPosition()]),
                                    binding.editTextAddress.getText().toString()
                            );
                            // If the callback function checkbox is checked,
                            // printer status callback and barcode scanner callback will start.
                            if (binding.checkBoxCallbackFunction.isChecked()) {
                                // Execute callback processing only when connection is successful
                                if(mSdkFunction.isAllowCallback()) {
                                    mSdkFunction.statusCallbackSample(MainFragment.this);
                                    mSdkFunction.barcodeScannerCallbackSample(MainFragment.this);
                                }
                            } else {
                                // If the callback function checkbox is not checked,
                                // printer status callback and barcode scanner callback will end.
                                mSdkFunction.statusCallbackSample(null);
                                mSdkFunction.barcodeScannerCallbackSample(null);
                            }

                            dismissProgressDialogAndShowResult(finalResultMessage);
                        }
                    }).start();
                }
            }
        });

        binding.buttonDisconnect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isRunning()) {
                    setRunningState(true) ;
                    showIndicatorDialog();
                    // Handle disconnect button click
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            // Perform disconnection
                            String finalResultMessage = mSdkFunction.disconnectSample();
                            dismissProgressDialogAndShowResult(finalResultMessage);
                        }
                    }).start();
                    initializeUI();
                }
            }
        });

        binding.buttonStandardModeSample.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isRunning()) {
                    setRunningState(true) ;
                    showIndicatorDialog();
                    // Handle standard mode sample button click
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            // Perform standard mode print sample
                            String finalResultMessage = mSdkFunction.standardModePrintSample();

                            dismissProgressDialogAndShowResult(finalResultMessage);
                        }
                    }).start();
                }
            }
        });

        binding.buttonPageModeSample.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isRunning()) {
                    setRunningState(true) ;
                    showIndicatorDialog();
                    // Handle page mode sample button click
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            // Perform page mode print sample
                            String finalResultMessage = mSdkFunction.pageModePrintSample();

                            dismissProgressDialogAndShowResult(finalResultMessage);
                        }
                    }).start();
                }
            }
        });

        binding.buttonSmartLabelSample.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isRunning()) {
                    setRunningState(true) ;
                    showIndicatorDialog();
                    // Handle smart label sample button click
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            // Perform smart label sample
                            String finalResultMessage = mSdkFunction.smartLabelSample();

                            dismissProgressDialogAndShowResult(finalResultMessage);
                        }
                    }).start();
                }
            }
        });

        binding.buttonDisplaySample.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isRunning()) {
                    setRunningState(true) ;
                    showIndicatorDialog();
                    // Handle display sample button click
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            // Initialize variables for displaying sample data
                            String resultMessage = "";
                            int total = 0;
                            int itemIndex = 0;
                            int paid = 0;
                            int change = 0;
                            String itemName = "";
                            int itemPrice = 0;

                            // Array of item names and prices
                            String[] itemNames;
                            // Change the display content to match the language of the device.
                            if (mLanguage.equals("ja")) {
                                itemNames = new String[]{
                                        "ブロッコリー",
                                        "バナナ",
                                        "ジャガイモ",
                                        "ブドウ",
                                        "エンドウ"
                                };
                            } else {
                                itemNames = new String[]{
                                        "BROCCOLI",
                                        "BANANA",
                                        "POTATO",
                                        "GRAPES",
                                        "PEAS"
                                };
                            }

                            int[] itemPrices = new int[]{
                                    132,
                                    186,
                                    391,
                                    116,
                                    100
                            };

                            // Begin the payment process
                            resultMessage = mSdkFunction.beginPaymentSample(total);
                            if (!resultMessage.isEmpty()) {
                                // Display error message if any
                                String finalResultMessage1 = resultMessage;

                                dismissProgressDialogAndShowResult(finalResultMessage1);
                                return;
                            }

                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                setRunningState(false) ;
                                throw new RuntimeException(e);
                            }

                            // Loop through items to display and calculate total
                            for (int i = 0; i < 5; i++) {
                                itemName = itemNames[itemIndex]; // Pick an item name
                                itemPrice = itemPrices[itemIndex];   // Pick an item price
                                itemIndex = (itemIndex + 1) % 5;
                                total += itemPrice;                   // Calculate total

                                // Register item for display
                                resultMessage = mSdkFunction.registerItemSample(total, itemName, itemPrice);
                                if (!resultMessage.isEmpty()) {
                                    // Display error message if any
                                    String finalResultMessage2 = resultMessage;

                                    dismissProgressDialogAndShowResult(finalResultMessage2);
                                    return;
                                }
                                try {
                                    Thread.sleep(300);
                                } catch (InterruptedException e) {
                                    throw new RuntimeException(e);
                                }
                            }
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }

                            // Calculate paid amount and change
                            paid = ((total + 999) / 1000) * 1000;
                            change = paid - total;

                            // Finish payment process
                            resultMessage = mSdkFunction.finishPaymentSample(total, paid, change);
                            if (!resultMessage.isEmpty()) {
                                // Display error message if any
                                String finalResultMessage3 = resultMessage;

                                dismissProgressDialogAndShowResult(finalResultMessage3);
                                return;
                            }
                            try {
                                Thread.sleep(3000);
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }

                            // Put the device in standby mode
                            resultMessage = mSdkFunction.standbySample();
                            if (!resultMessage.isEmpty()) {
                                // Display error message if any
                                String finalResultMessage4 = resultMessage;

                                dismissProgressDialogAndShowResult(finalResultMessage4);
                                return;
                            }

                            dismissProgressDialogAndShowResult("Display Sample success");
                        }
                    }).start();
                }
            }
        });

        binding.buttonSendDataFile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isRunning()) {
                    setRunningState(true) ;
                    // Handle button click to send data file
                    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                    intent.setType("*/*");
                    fragmentResultLauncher_sendDataFileSample.launch(intent);
                }
            }
        });

        binding.buttonPrintPdf.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isRunning()) {
                    setRunningState(true) ;
                    // Handle button click to print PDF
                    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                    intent.setType("application/pdf");
                    fragmentResultLauncher_printPdfSample.launch(intent);
                }
            }
        });

        binding.buttonOpenDrawer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isRunning()) {
                    setRunningState(true) ;
                    showIndicatorDialog();
                    // Handle button click to open drawer
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            // Perform action to open drawer
                            String finalResultMessage = mSdkFunction.openDrawerSample();

                            dismissProgressDialogAndShowResult(finalResultMessage);
                        }
                    }).start();
                }
            }
        });
    }

    private void dismissProgressDialogAndShowResult(String msg){
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                // Dismiss indicator dialog and show result message
                dismissIndicatorDialog();
                new MessageDialogFragment(msg).show(getChildFragmentManager(), "message_dialog");
                setRunningState(false) ;
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        requireActivity().addMenuProvider(menuProvider, getViewLifecycleOwner(), Lifecycle.State.RESUMED);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        // Nullify the binding object to release memory
        binding = null;
    }

    private void initializeUI() {
        binding.editTextPrinterStatus.setText("-");
        binding.editTextScannerStatus.setText("-");
        binding.editTextScannedData.setText("-");
    }

    // Activity result launcher for sending data file sample
    final ActivityResultLauncher<Intent> fragmentResultLauncher_sendDataFileSample =
            registerForActivityResult(new StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        showIndicatorDialog();
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                Intent intent = result.getData();
                                String finalResultMessage = mSdkFunction.sendDataFileSample(Objects.requireNonNull(intent).getDataString());

                                dismissProgressDialogAndShowResult(finalResultMessage);
                            }
                        }).start();
                    }
                    setRunningState(false) ;
                });

    // Activity result launcher for print PDF sample
    final ActivityResultLauncher<Intent> fragmentResultLauncher_printPdfSample =
            registerForActivityResult(new StartActivityForResult(),
                    result -> {
                        if (result.getResultCode() == Activity.RESULT_OK) {
                            showIndicatorDialog();
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    Intent intent = result.getData();
                                    String finalResultMessage = mSdkFunction.printPdfSample(Objects.requireNonNull(intent).getDataString());

                                    dismissProgressDialogAndShowResult(finalResultMessage);
                                }
                            }).start();
                        }
                        setRunningState(false) ;
                    });

    // Activity result launcher for permission request
    final ActivityResultLauncher<String> fragmentResultLauncher_permissionRequest =
            registerForActivityResult(new RequestPermission(),
                isGranted -> {
                    if (isGranted) {
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                // For Android 12 or higher
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                                    if ((PermissionChecker.checkSelfPermission(requireActivity(), android.Manifest.permission.BLUETOOTH_CONNECT) != PermissionChecker.PERMISSION_GRANTED)
                                            || (PermissionChecker.checkSelfPermission(requireActivity(), android.Manifest.permission.BLUETOOTH_SCAN) != PermissionChecker.PERMISSION_GRANTED)) {
                                        fragResultLauncher_PermsAndroid12.launch(new String[]{android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_SCAN});
                                        return;
                                    }
                                }
                                // For Android 10 or higher
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                                    checkLocationRequest();
                                    return;
                                }
                                NavHostFragment.findNavController(MainFragment.this)
                                        .navigate(R.id.action_MainFragment_to_DeviceFragment);
                            }
                        });
                    }
                });

    // Activity result launcher for permission requests on Android 12 and above
    final ActivityResultLauncher<String[]> fragResultLauncher_PermsAndroid12 =
            registerForActivityResult(new RequestMultiplePermissions(),
                permissions -> {
                    if (Boolean.TRUE.equals(permissions.get(android.Manifest.permission.BLUETOOTH_CONNECT)) &&
                            Boolean.TRUE.equals(permissions.get(android.Manifest.permission.BLUETOOTH_SCAN))) {
                        mHandler.post(() -> {
                            // For Android 10 or higher
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                                checkLocationRequest();
                                return;
                            }
                            NavHostFragment.findNavController(MainFragment.this).navigate(R.id.action_MainFragment_to_DeviceFragment);
                        });
                    }
                });

    // Check location request and navigate accordingly
    private void checkLocationRequest(){
        final LocationRequest locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest).setAlwaysShow(true);
        SettingsClient client = LocationServices.getSettingsClient(requireActivity());
        Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build());
        task.addOnCompleteListener(new OnCompleteListener<LocationSettingsResponse>() {
            @Override
            public void onComplete(@NonNull Task<LocationSettingsResponse> task) {
                try {
                    task.getResult(ApiException.class);
                    NavHostFragment.findNavController(MainFragment.this)
                            .navigate(R.id.action_MainFragment_to_DeviceFragment);
                } catch (ApiException exception) {
                    switch (exception.getStatusCode()) {
                        case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                            try {
                                // Request for location information setting
                                ((ResolvableApiException) exception).startResolutionForResult(requireActivity(), REQUEST_LOCATION_SETTING_RESOLUTION);
                                return;
                            } catch (IntentSender.SendIntentException e) {
                                // Ignore the error.
                            } catch (ClassCastException e) {
                                // Ignore, should be an impossible error.
                            }
                            break;
                        case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                            break;
                    }
                }
            }
        });
    }

    // Show indicator dialog
    private void showIndicatorDialog() {
        mIndicatorDialog = new IndicatorDialogFragment(null);
        mIndicatorDialog.setCancelable(false);// Prevent cancellation
        mIndicatorDialog.show(getChildFragmentManager(), "indicator_dialog");
    }
    // Dismiss indicator dialog
    private void dismissIndicatorDialog() {
        mIndicatorDialog.dismiss();
    }

    private void setRunningState(boolean state) {
        isRunning = state;
    }

    private boolean isRunning() {
        return isRunning;
    }

    @Override
    public void onStatusChanged(int currentStatus) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                // Determine if fragment is added to activity
                if (isAdded()){
                    // Update printer status to EditText
                    if(mSdkFunction.getPrinterManager() .getPrinterModel() != PrinterManager.PRINTER_MODEL_DPU_S245
                            && mSdkFunction.getPrinterManager().getPrinterModel() != PrinterManager.PRINTER_MODEL_DPU_S445){
                        binding.editTextPrinterStatus.setText(getString(R.string.msg_status, currentStatus));
                    }else{
                        binding.editTextPrinterStatus.setText(getString(R.string.msg_status_dpu, currentStatus));
                    }
                }
            }
        });
    }

    @Override
    public void onBarcodeScannerReadData(byte[] data) {
        String barcodeData = "Encoding failed!!";
        if (!isAdded()) {
            return;
        }
        if (binding.checkBoxAsString.isChecked()) {
            // String notation
            try {
                barcodeData = new String(data, "SJIS");
            } catch (UnsupportedEncodingException ex) {
                ex.printStackTrace();
                barcodeData = "Encoding failed!!";
            }
        } else {
            // Hexadecimal notation
            StringBuilder sb = new StringBuilder(2 * data.length);
            for(byte b: data) {
                sb.append(String.format("%02x", b&0xff) );
            }
            barcodeData = sb.toString();
        }

        String finalBarcodeData = barcodeData;
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (isAdded()) {
                    binding.editTextScannedData.setText(finalBarcodeData);
                }
            }
        });
    }

    @Override
    public void onBarcodeScannerChangedOnline() {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (isAdded()) {
                    binding.editTextScannerStatus.setText("Online");
                }
            }
        });
    }

    @Override
    public void onBarcodeScannerChangedOffline() {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (isAdded()) {
                    binding.editTextScannerStatus.setText("Offline");
                }
            }
        });
    }

    private void showSettingFragment(){
        // Navigate to SettingsFragment
        Bundle bundle = new Bundle();
        bundle.putInt(MainActivity.BUNDLE_KEY_SOCKET_KEEPING_TIME, mSdkFunction.getPrinterManager().getSocketKeepingTime());
        bundle.putInt(MainActivity.BUNDLE_KEY_SEND_TIMEOUT, mSdkFunction.getPrinterManager().getSendTimeout());
        bundle.putInt(MainActivity.BUNDLE_KEY_RECEIVE_TIMEOUT, mSdkFunction.getPrinterManager().getReceiveTimeout());
        bundle.putInt(MainActivity.BUNDLE_KEY_CODE_PAGE, mSdkFunction.getPrinterManager().getCodePage());
        bundle.putInt(MainActivity.BUNDLE_KEY_INTERNATION_CHAR, mSdkFunction.getPrinterManager().getInternationalCharacter());
        int secureConnection = 0;
        if (!mSdkFunction.getSecureConnection()){
            secureConnection = 1;
        }
        bundle.putInt(MainActivity.BUNDLE_KEY_SECURE_CONNECTION, secureConnection);

        NavHostFragment.findNavController(MainFragment.this)
                .navigate(R.id.action_MainFragment_to_SettingsFragment,bundle);
    }

}