package it.integry.integrywmsnative.core.expansion;

import android.app.Dialog;

import androidx.fragment.app.Fragment;

import java.util.ArrayList;
import java.util.List;

import it.integry.integrywmsnative.core.barcode_reader.BarcodeManager;
import it.integry.integrywmsnative.core.interfaces.IPoppableActivity;
import it.integry.integrywmsnative.core.utility.UtilityExceptions;
import it.integry.integrywmsnative.core.utility.UtilityProgress;
import it.integry.integrywmsnative.ui.ElevatedToolbar;

public abstract class BaseFragment extends Fragment {

    protected Dialog mCurrentProgress;

    protected ElevatedToolbar mToolbar;

    protected final List<Runnable> mOnPreDestroyList = new ArrayList<>();




    public void setScrollToolbar(ElevatedToolbar toolbar) {
        mToolbar = toolbar;
    }


    public void addOnPreDestroy(Runnable onPreDestroy) {
        this.mOnPreDestroyList.add(onPreDestroy);
    }






    public void onLoadingStarted() {
        new Thread(() -> {
            BarcodeManager.disable();
            this.openProgress();
        }).start();
    }

    public void onLoadingEnded() {
        new Thread(() -> {
            this.closeProgress();
            BarcodeManager.enable();
        }).start();
    }

    public void onError(Exception ex) {
        this.getActivity().runOnUiThread(() -> {
            this.closeProgress();
            UtilityExceptions.defaultException(getActivity(), ex, mCurrentProgress);
            BarcodeManager.enable();
        });
    }


    @Override
    public void onDestroy() {
        super.onDestroy();

        for (Runnable onPreDestroy : mOnPreDestroyList) {
            onPreDestroy.run();
        }
    }

    protected void openProgress() {
            getActivity().runOnUiThread(() -> {
                if (this.mCurrentProgress == null) {
                    this.mCurrentProgress = UtilityProgress.createDefaultProgressDialog(getActivity());
                }
            });
    }

    protected void closeProgress() {
            getActivity().runOnUiThread(() -> {
                if (mCurrentProgress != null) {
                    mCurrentProgress.dismiss();
                    mCurrentProgress = null;
                }
            });
    }

    protected void popMe() {
        ((IPoppableActivity) requireActivity()).pop();
    }
}
