package com.adealink.weparty.commonui.viewstub;

import android.view.View;
import android.view.ViewStub;
import android.view.ViewStub.OnInflateListener;

import androidx.annotation.NonNull;

/**
 * This class represents a ViewStub before and after inflation. Before inflation,
 * the ViewStub is accessible. After inflation, the root View of the inflated layout
 * will be available. If the inflated layout has data binding, the ViewDataBinding for the inflated
 * View is accessible.
 */
public class ViewStubProxy {
    private View mRoot;
    private ViewStub mViewStub;

    public ViewStubProxy(@NonNull ViewStub viewStub) {
        mViewStub = viewStub;
        OnInflateListener mProxyListener = new OnInflateListener() {
            @Override
            public void onInflate(ViewStub stub, View inflated) {
                mRoot = inflated;
                mViewStub = null;
            }
        };
        viewStub.setOnInflateListener(mProxyListener);
    }

    public ViewStubProxy() {
    }

    public static ViewStubProxy findViewStubById(View container, int id) {
        return new ViewStubProxy(container.<ViewStub>findViewById(id));
    }

    public View inflate() {
        return mRoot != null ? mRoot : mViewStub.inflate();
    }

    /**
     * Returns <code>true</code> if the ViewStub has replaced itself with the inflated layout
     * or <code>false</code> if not.
     *
     * @return <code>true</code> if the ViewStub has replaced itself with the inflated layout
     * or <code>false</code> if not
     */
    public boolean isInflated() {
        return mRoot != null;
    }

    /**
     * Returns the root View of the layout replacing the ViewStub once it has been inflated.
     * <code>null</code> is returned prior to inflation.
     *
     * @return the root View of the layout replacing the ViewStub once it has been inflated.
     * <code>null</code> is returned prior to inflation
     */
    public View getRoot() {
        return mRoot;
    }

    /**
     * Returns the ViewStub in the layout or <code>null</code> if the ViewStub has been inflated.
     *
     * @return the ViewStub in the layout or <code>null</code> if the ViewStub has been inflated.
     */
    public ViewStub getViewStub() {
        return mViewStub;
    }
}
