package it.integry.integrywmsnative.core.di.binders;

import androidx.databinding.BindingAdapter;
import androidx.core.util.Pair;

import net.cachapa.expandablelayout.ExpandableLayout;

import it.integry.integrywmsnative.R;
import it.integry.integrywmsnative.core.di.BindableBoolean;

public class ExpandableLayoutBinders {

    @BindingAdapter("app:el_expanded_bind")
    public static void bindExpandableLayout(final ExpandableLayout view, final BindableBoolean bindableBoolean) {

        Pair<BindableBoolean, ExpandableLayout.OnExpansionUpdateListener> pair = (Pair) view.getTag(R.id.bound_observable);
        if (pair == null || pair.first != bindableBoolean) {
            if (pair != null) {
                view.setOnExpansionUpdateListener(null);
            }

            ExpandableLayout.OnExpansionUpdateListener watcher = new ExpandableLayout.OnExpansionUpdateListener() {
                @Override
                public void onExpansionUpdate(float expansionFraction, int state) {
                    if(view.isExpanded() == bindableBoolean.get()) return;
                    bindableBoolean.set(state == 1);
                }
            };

            view.setTag(R.id.bound_observable, new Pair<>(bindableBoolean, watcher));
            view.setOnExpansionUpdateListener(watcher);
        }
        boolean newValue = bindableBoolean.get();
        if (!view.isExpanded() == newValue) {
            if(newValue) view.expand(true);
            else view.collapse(true);
        }
    }

}
