package it.integry.integrywmsnative.core.expansion.view;

import android.view.View;

import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableList;
import androidx.recyclerview.widget.RecyclerView;

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

import it.integry.integrywmsnative.core.expansion.OnListGeneralChangedCallback;

public abstract class ExtendedRecyclerView<T, VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH> {
    protected ArrayList<T> mDataset;
    private View mEmptyView;

    public ExtendedRecyclerView(ObservableArrayList<T> myDataset) {
        mDataset = myDataset;

        myDataset.addOnListChangedCallback(new OnListGeneralChangedCallback() {
            @Override
            public void onChanged(ObservableList sender) {
                notifyDataSetChanged();
                checkIfEmpty();
            }
        });

        checkIfEmpty();
    }

    @Override
    public void onViewRecycled(VH holder) {
        super.onViewRecycled(holder);
    }

    @Override
    public int getItemCount() {
        return mDataset.size();
    }

    public void clearDataset() {
        mDataset.clear();
        notifyDataSetChanged();
    }

    public void updateDataset(List<T> updatedDataset) {
        mDataset.clear();

        if(updatedDataset != null && !updatedDataset.isEmpty()) {
            mDataset.addAll(updatedDataset);
        }

        notifyDataSetChanged();
    }

    public void addDataset(List<T> insertDataset) {
        if(insertDataset != null && !insertDataset.isEmpty()) {
            mDataset.addAll(insertDataset);
            notifyDataSetChanged();
        }
    }

    public ExtendedRecyclerView<T, VH> setEmptyView(View emptyView) {
        this.mEmptyView = emptyView;
        this.checkIfEmpty();
        return this;
    }

    private void checkIfEmpty() {
        if (mEmptyView != null) {
            final boolean emptyViewVisible = getItemCount() == 0;
            mEmptyView.setVisibility(emptyViewVisible ? View.VISIBLE : View.GONE);
        }
    }
}
