package tech.starwin.widget;

import android.content.Context;
import android.support.annotation.Nullable;
import android.text.Editable;
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/25.
 * 标题 + 文本   布局
 * 第一个Child 默认为Title
 * 当EditText/TextView中有内容输入时，显示Title, 反之隐藏（无输入内容时直接用hintText展示）
 */
public class TitleSpan extends LinearLayout {
    public TitleSpan(Context context) {
        super(context);
    }

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

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

    @Override
    public void onViewAdded(final View child) {
        super.onViewAdded(child);
        TextWatcher textWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (getChildCount() > 1 && indexOfChild(child) != 0) {
                    if (TextUtils.isEmpty(s.toString().replace(" ", ""))) {
                        getChildAt(0).setVisibility(GONE);
                    } else {
                        getChildAt(0).setVisibility(VISIBLE);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        };

        if (child instanceof EditText) {
            ((EditText) child).addTextChangedListener(textWatcher);
        } else if (child instanceof TextView) {
            ((TextView) child).addTextChangedListener(textWatcher);
        } else if (child instanceof SpanButton) {
            ((SpanButton) child).addTextChangedListener(textWatcher);
        }
    }
}
