package com.ydl.audioim.widget;

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

import java.lang.ref.WeakReference;

/**
 * Created on 2018/1/18  13:02
 *
 * @author Z
 * @version : 1.0.0
 * 辅助给ZDialog的布局文件设置属性
 */

public class ZDialogViewHelper {
    private View mContentView;
    private SparseArray<WeakReference<View>> mViews;
    private Context mContext;

    public ZDialogViewHelper(Context context, int contentResId) {
        this();
        mContext = context;
        mContentView = LayoutInflater.from(mContext).inflate(contentResId, null);
    }

    public ZDialogViewHelper() {
        mViews = new SparseArray<>();
    }

    public View getContentView() {
        return mContentView;
    }

    public void setContentView(View contentView) {
        this.mContentView = contentView;
    }

    /**
     * @param viewId viewId
     * @param strId  strId
     */
    public void setText(int viewId, int strId) {
        setText(viewId, mContext.getResources().getString(strId));
    }

    /**
     * 通过id 给控件设置文本
     *
     * @param viewId       viewId
     * @param charSequence 文本类容
     */
    public void setText(int viewId, CharSequence charSequence) {
        TextView view = getView(viewId);
        if (charSequence != null && charSequence.length() > 0) {
            view.setText(charSequence);
        }
    }

    /**
     * 通过id  找到相应的控件
     *
     * @param viewId viewId
     * @param <T>    具体的类型
     * @return view
     */
    @SuppressWarnings("unchecked")
    private <T extends View> T getView(int viewId) {
        WeakReference<View> weakReference = mViews.get(viewId);
        View view = null;
        if (weakReference != null) {
            view = weakReference.get();
        }
        if (view == null) {
            view = mContentView.findViewById(viewId);
            if (view != null) {
                mViews.put(viewId, new WeakReference<>(view));
            }
        }
        return (T) view;
    }

    public EditText getEditText(int viewId) {
        return getView(viewId);
    }

    public View findView(int viewId) {
        return getView(viewId);
    }

    /**
     * 设置点击事件
     *
     * @param viewId          viewId
     * @param onClickListener onClickListener
     */
    public void setOnClickListener(int viewId, View.OnClickListener onClickListener) {
        View view = getView(viewId);
        if (view != null) {
            view.setOnClickListener(onClickListener);
        }
    }
}
