package com.xplora.xpsettings.SKKeyboard;

import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import java.lang.reflect.Method;

public class SKEditText extends EditText implements View.OnFocusChangeListener {

    private SKKeyboardUtils mSKKeyUtils;

    public SKEditText(Context context) {
        super(context);
        setOnFocusChangeListener(this);
    }

    public SKEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        setOnFocusChangeListener(this);
    }

    public SKEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setOnFocusChangeListener(this);
    }

    public SKEditText(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        setOnFocusChangeListener(this);
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            //不显示系统键盘
            closeSystemKeyboard();

            //用来初始化我们的软键盘
            SKKeyboardUtils.getInstance().createSKKeyboard(getContext(), this);
            SKKeyboardUtils.getInstance().openSKKeyboard();
        } else {
            SKKeyboardUtils.getInstance().closeSKKeyboard();
        }
    }

    private void closeSystemKeyboard() {
        InputMethodManager imm = (InputMethodManager)getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getWindowToken(), 0);
        ((Activity)getContext()).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        try {
            Class<EditText> cls = EditText.class;
            Method setShowSoftInputOnFocus;
            setShowSoftInputOnFocus = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
            setShowSoftInputOnFocus.setAccessible(true);
            setShowSoftInputOnFocus.invoke(this, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
