package com.kfzs.libs.widget;

import android.content.Context;
import android.support.v7.widget.AppCompatAutoCompleteTextView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.View;

/**
 * Created by guoxin on 2018/4/2.
 */

public class CompleteCommitEditText extends AppCompatAutoCompleteTextView implements TextWatcher,View.OnFocusChangeListener{

    private static final String TAG = "CompleteCommitEditText";
    private String lastText = "";

    private OnCompleteEditListener onCompleteEditListener;

    private boolean afterTextChangedCanComplete = false;

    Runnable recorderRunnable = new Runnable() {
        @Override
        public void run() {
            lastText = getText().toString();
        }
    };


    public CompleteCommitEditText(Context context) {
        super(context);
        init();
    }

    public CompleteCommitEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CompleteCommitEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init(){
        addTextChangedListener(this);
        setOnFocusChangeListener(this);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {

        if(isFocusable() && afterTextChangedCanComplete){
            String curText = getText().toString();
            if(!TextUtils.equals(lastText,curText)){
                if (onCompleteEditListener != null) {
                    onCompleteEditListener.onCompleteEdit(curText);
                }
                postDelayed(recorderRunnable,500);
            }
        }
    }

    public void setAfterTextChangedCanComplete(boolean afterTextChangedCanComplete) {
        this.afterTextChangedCanComplete = afterTextChangedCanComplete;
    }

    public void setOnCompleteEditListener(OnCompleteEditListener onCompleteEditListener) {
        this.onCompleteEditListener = onCompleteEditListener;
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if(!hasFocus){//失去焦点
            String curText = getText().toString();
            if(!TextUtils.equals(curText,lastText)){//这里防止重新获取焦点后，上次填入的数据与这次一样，会引起重复提交
                if(onCompleteEditListener != null){
                    onCompleteEditListener.onCompleteEdit(curText);
                }
            }
            lastText = curText;
        }
    }


    public interface OnCompleteEditListener{
        void onCompleteEdit(String text);
    }
}
