package tech.starwin.widget;

import android.content.Context;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * Created by SiKang on 2018/10/24.
 * 行按钮，用于 文字 + 图标 的itemList型布局（避免Layout 和 child 分开处理的复杂操作）
 * 提供 setText() 和 setOnclick()，默认将第一个TextView类型的 child 作为 setText() 对象
 */
public class SpanButton extends LinearLayout {
    private TextWatcher watcher;

    public SpanButton(Context context) {
        super(context);
        init(null);
    }

    public SpanButton(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public SpanButton(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    private void init(AttributeSet attrs) {
        setOrientation(HORIZONTAL);
    }


    @Override
    public void setOnClickListener(@Nullable OnClickListener l) {
        super.setOnClickListener(l);
        for (int i = 0; i < getChildCount(); i++) {
            getChildAt(i).setClickable(false);
        }
    }

    @Override
    public void onViewAdded(View child) {
        super.onViewAdded(child);
        bindTextWatcher(child);
    }

    /**
     * 为第一个为TextView类型的child setText
     */
    public void setText(String text) {
        if (!TextUtils.isEmpty(text)) {
            for (int i = 0; i < getChildCount(); i++) {
                View view = getChildAt(i);
                if (view instanceof TextView) {
                    ((TextView) view).setText(text);
                    return;
                }
            }
        }
    }

    public CharSequence getText() {
        for (int i = 0; i < getChildCount(); i++) {
            View view = getChildAt(i);
            if (view instanceof TextView) {
                return ((TextView) view).getText();
            }
        }
        return "";
    }


    public TextView getCotentView() {
        for (int i = 0; i < getChildCount(); i++) {
            View view = getChildAt(i);
            if (view instanceof TextView) {
                return (TextView) view;
            }
        }
        return null;
    }


    public void addTextChangedListener(TextWatcher watcher) {
        this.watcher = watcher;
        for (int i = 0; i < getChildCount(); i++) {
            bindTextWatcher(getChildAt(i));
        }
    }

    public void bindTextWatcher(View child) {
        if (watcher != null) {
            if (child instanceof TextView) {
                ((TextView) child).addTextChangedListener(watcher);
            } else if (child instanceof EditText) {
                ((EditText) child).addTextChangedListener(watcher);
            }
        }
    }

}
