package com.kozen.kozenui.dialog;

import android.content.Context;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.text.method.KeyListener;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.kozen.printerhelper.R;

public class EditTextDialog extends BaseEditDialog {

    private static EditTextDialog instance;

    private View clear;

    private EditTextDialog() {
    }


    public static EditTextDialog getInstance(){
        if(instance == null){
            instance = new EditTextDialog();
        }
        return instance;
    }

    @Override
    protected void init() {
        editText = (EditText) dialog.findViewById(R.id.edit);
        clear = dialog.findViewById(R.id.clear);
        editText.addTextChangedListener(textWatcher);
        clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                editText.setText("");
            }
        });
    }

    @Override
    protected void onDialogCancel() {
        editText.setText("");
        instance = null;

    }


    TextWatcher textWatcher = new TextWatcher(){
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int start, int count, int after) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            if(editable.length()>0){
                clear.setVisibility(View.VISIBLE);
            }else{
                clear.setVisibility(View.INVISIBLE);
            }
        }
    };

    public void showKeyboard() {
        if(editText!=null){
            //设置可获得焦点
            editText.setFocusable(true);
            editText.setFocusableInTouchMode(true);
            //请求获得焦点
            editText.requestFocus();
            //调用系统输入法
            InputMethodManager inputManager = (InputMethodManager) editText
                    .getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.showSoftInput(editText, 0);
        }
    }

    /**
     * 设置输入框的文字
     * @param content
     */
    public void setText(String content){
        editText.setText(content);
        editText.setSelection(content.length());
    }

    public EditText getEditText(){
        return this.editText;
    }

    /**
     * 设置输入框的最大长度
     * @param num
     */
    public void setMaxLength(int num){
        editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(num)});
    }

    /**
     * 设置输入框提示文字
     * @param text
     */
    public void setHintText(String text){
        editText.setHint(text);
    }

    public void setKeyListen(KeyListener listen){
        editText.setKeyListener(listen);
    }
}

