package com.kfzs.android.view.widget;

import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;

/**
 * for EditText action of IME action and other
 * <pre>
 *     sinlov
 *
 *     /\__/\
 *    /`    '\
 *  ≈≈≈ 0  0 ≈≈≈ Hello world!
 *    \  --  /
 *   /        \
 *  /          \
 * |            |
 *  \  ||  ||  /
 *   \_oo__oo_/≡≡≡≡≡≡≡≡o
 *
 * </pre>
 * Created by sinlov on 17/4/18.
 */
public class EditTextActionUtils {

    private final IEditTextActionJob iEditTextActionJob;
    private final EditText editText;

    public void watchEnterAction() {
        View.OnKeyListener thisKeyListener = new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (null != event) {
                    int action = event.getAction();
                    if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
                        if (KeyEvent.ACTION_UP == action) {
                            return iEditTextActionJob.onIMEAction(keyCode, event);
                        }
                    }
                }
                return false;
            }
        };
        editText.setOnKeyListener(thisKeyListener);
    }

    private EditTextActionUtils(Build build) {
        if (build.iEditTextActionJob == null) {
            throw new NullPointerException("you are not use setEditTextActionJob()");
        }
        if (build.editText == null) {
            throw new NullPointerException("you are not use setEditText()");
        }
        this.iEditTextActionJob = build.iEditTextActionJob;
        this.editText = build.editText;
    }

    public final static class Build {
        private IEditTextActionJob iEditTextActionJob;
        private EditText editText;

        public Build setEditTextActionJob(IEditTextActionJob iEditTextActionJob) {
            this.iEditTextActionJob = iEditTextActionJob;
            return this;
        }

        public Build setEditText(EditText editText) {
            this.editText = editText;
            return this;
        }

        public EditTextActionUtils create() {
            return new EditTextActionUtils(this);
        }
    }
}
