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.
 * 行按钮
 */
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);
    }

    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);
            }
        }
    }

}
