package com.mayi.fastdevelop.view.dialog;

import android.content.Context;
import android.util.SparseArray;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.StringRes;

public class DialogViewHolder {
    private final SparseArray<View> mViews;
    private View mDialogView;

    private DialogViewHolder(Context context, int layoutId) {
        this.mViews = new SparseArray<>();
        mDialogView = View.inflate(context, layoutId, null);
    }

    public static DialogViewHolder get(Context context, int layoutId) {
        return new DialogViewHolder(context, layoutId);
    }

    public View getConvertView() {
        return mDialogView;
    }

    public DialogViewHolder setText(int viewId, CharSequence text) {
        TextView view = getView(viewId);
        view.setText(text);
        return this;
    }

    public DialogViewHolder setText(int viewId, @StringRes int redId) {
        TextView view = getView(viewId);
        view.setText(redId);
        return this;
    }

    /**
     * 设置view 显示状态
     *
     * @param viewId    view id
     * @param viewState View.VISIBLE / GONE /INVISIBLE
     * @return
     */
    public DialogViewHolder setViewVisibleState(int viewId, int viewState) {
        View view = getView(viewId);
        view.setVisibility(viewState);
        return this;
    }

    /**
     * 设置点击事件
     */
    public DialogViewHolder setOnClick(int viewId, View.OnClickListener onClick) {
        View view = getView(viewId);
        view.setOnClickListener(onClick);
        return this;
    }

    /**
     * Through control the Id of the access to control, if not join views
     *
     * @param viewId
     * @return
     */
    private <T extends View> T getView(int viewId) {
        View view = mViews.get(viewId);
        if (view == null) {
            view = mDialogView.findViewById(viewId);
            mViews.put(viewId, view);
        }
        return (T) view;
    }
}
