package com.xplora.xpsettings.Utils;

import android.app.Activity;
import android.content.Context;
import android.inputmethodservice.Keyboard;
import android.inputmethodservice.KeyboardView;
import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import com.xplora.xpsettings.R;

import java.util.Locale;
import java.util.Objects;

public class KeyUtils {

    private KeyboardView mKeyboardView;
    private final Keyboard mKeyboard;
    private final Keyboard mKeyboardShifted;
    private final Keyboard mKeyboardShiftLocked;
    private final Keyboard mKeyboardSymbols;
    private final Keyboard mKeyboardSymbolsShifted;
    private final EditText mEditText;
    private boolean isShiftLocked = false;

    public KeyUtils(Context context, EditText editText) {
        mEditText = editText;

        mKeyboard = new Keyboard(context, R.xml.keyboard_abc);
        mKeyboard.setShifted(false);
        mKeyboardShifted = new Keyboard(context, R.xml.keyboard_abc_shifted);
        mKeyboardShifted.setShifted(true);
        mKeyboardShiftLocked = new Keyboard(context, R.xml.keyboard_abc_shift_locked);
        mKeyboardShiftLocked.setShifted(true);
        mKeyboardSymbols = new Keyboard(context, R.xml.keyboard_symbols);
        mKeyboardSymbols.setShifted(false);
        mKeyboardSymbolsShifted = new Keyboard(context, R.xml.keyboard_symbols_shifted);
        mKeyboardSymbolsShifted.setShifted(true);

        try {
            mKeyboardView = ((Activity) context).findViewById(R.id.main_keyview);
            mKeyboardView.setKeyboard(mKeyboard);
            mKeyboardView.setPreviewEnabled(false);   //这个是，效果图按住是出来的预览图。
            mKeyboardView.setEnabled(true);
            mKeyboardView.setVisibility(View.VISIBLE);

            KeyboardView.OnKeyboardActionListener mListener = new KeyboardView.OnKeyboardActionListener() {
                @Override
                public void onKey(int primaryCode, int[] keyCodes) {
                    Log.d("wifikey", "onKey : " + primaryCode);
                    if (primaryCode == KEY_CODES.KEY_SHIFT.CODES) {
                        doShift();
                    } else if (primaryCode == KEY_CODES.KEY_SWITCH.CODES) {
                        doSwitch();
                    } else {
                        updateText(primaryCode);
                    }
                }

                @Override
                public void onPress(int primaryCode) { }
                @Override
                public void onRelease(int primaryCode) { }
                @Override
                public void onText(CharSequence charSequence) { }
                @Override
                public void swipeLeft() { }
                @Override
                public void swipeRight() { }
                @Override
                public void swipeDown() { }
                @Override
                public void swipeUp() { }

            };
            mKeyboardView.setOnKeyboardActionListener(mListener);
        } catch (Exception ignored) {
        }
    }

    private void doShift() {
        Keyboard current = mKeyboardView.getKeyboard();
        boolean shiftStatus = mKeyboardView.getKeyboard().isShifted();
        if (current.equals(mKeyboard) || current.equals(mKeyboardShifted) || current.equals(mKeyboardShiftLocked)) {
            if (!shiftStatus) {
                mKeyboardView.setKeyboard(mKeyboardShifted);
            } else if (!isShiftLocked) {
                isShiftLocked = true;
                mKeyboardView.setKeyboard(mKeyboardShiftLocked);
            } else {
                isShiftLocked = false;
                mKeyboardView.setKeyboard(mKeyboard);
            }
        } else {
            if(!shiftStatus) {
                isShiftLocked = true;
                mKeyboardView.setKeyboard(mKeyboardSymbolsShifted);
            } else {
                isShiftLocked = false;
                mKeyboardView.setKeyboard(mKeyboardSymbols);
            }
        }
    }

    private void doSwitch() {
        Keyboard current = mKeyboardView.getKeyboard();
        if (current.equals(mKeyboard) || current.equals(mKeyboardShifted) || current.equals(mKeyboardShiftLocked)) {
            isShiftLocked = false;
            mKeyboardView.setKeyboard(mKeyboardSymbols);
        } else {
            isShiftLocked = false;
            mKeyboardView.setKeyboard(mKeyboard);
        }
    }

    private void updateText(int primaryCode) {
        String content = KEY_CODES.getLabel(primaryCode);
        boolean shiftStatus = mKeyboardView.getKeyboard().isShifted();
        if (primaryCode != KEY_CODES.KEY_DEL.CODES
                && primaryCode != KEY_CODES.KEY_SPACE.CODES
                && shiftStatus) {
            assert content != null;
            content = content.toUpperCase(Locale.ROOT);
            if (!isShiftLocked) {
                mKeyboardView.setKeyboard(mKeyboard);
            }
        }

        int index = mEditText.getSelectionStart();
        Editable contentText = mEditText.getText();
        switch (Objects.requireNonNull(content)) {
            case "del":
                if(index == 0) break;
                contentText.delete(index - 1, index);
                break;
            case "space":
                contentText.append(" ");
                break;
            default:
                contentText.append(content);
                break;

        }
        mEditText.setText(contentText);
        mEditText.setSelection(contentText.length());
    }

    enum KEY_CODES {
        KEY_0(48, "0"),
        KEY_1(49, "1"),
        KEY_2(50, "2"),
        KEY_3(51, "3"),
        KEY_4(52, "4"),
        KEY_5(53, "5"),
        KEY_6(54, "6"),
        KEY_7(55, "7"),
        KEY_8(56, "8"),
        KEY_9(57, "9"),

        KEY_SYMBOLS_AT(64, "@"),
        KEY_SYMBOLS_POUND(35, "#"),
        KEY_SYMBOLS_PERCENT(37, "%"),
        KEY_SYMBOLS_AND(38, "&"),
        KEY_SYMBOLS_STAR(42, "*"),
        KEY_SYMBOLS_PLUS(43, "+"),
        KEY_SYMBOLS_MINUS(45, "-"),
        KEY_SYMBOLS_EQUALS(61, "="),
        KEY_SYMBOLS_LEFT_PAREN(40, "("),
        KEY_SYMBOLS_RIGHT_PAREN(41, ")"),
        KEY_SYMBOLS_TILDE(126, "~"),
        KEY_SYMBOLS_SEMI_COLON(34, "\""),
        KEY_SYMBOLS_APOSTROPHE(39, "'"),
        KEY_SYMBOLS_COLON(58, ":"),
        KEY_SYMBOLS_SEMICOLON(59, ";"),
        KEY_SYMBOLS_SLASH(47, "/"),
        KEY_SYMBOLS_EXCLAMATION(33, "!"),

        KEY_SYMBOLS_CARET(94, "^"),
        KEY_SYMBOLS_YUAN(165, "￥"),
        KEY_SYMBOLS_DOLLAR(36, "$"),
        KEY_SYMBOLS_LEFT_BRACKET(91, "["),
        KEY_SYMBOLS_RIGHT_BRACKET(93, "]"),
        KEY_SYMBOLS_UNDERLINE(95, "_"),
        KEY_SYMBOLS_LEFT_BRACES(123, "{"),
        KEY_SYMBOLS_RIGHT_BRACES(125, "}"),

        KEY_SYMBOLS_GRAVE(96, "`"),
        KEY_SYMBOLS_LEFT_ANGLE_BRACKET(60, "<"),
        KEY_SYMBOLS_RIGHT_ANGLE_BRACKET(62, ">"),
        KEY_SYMBOLS_BACKSLASH(92, "\\"),
        KEY_SYMBOLS_DELIMITER(124, "|"),

        KEY_A(97, "a"),
        KEY_B(98, "b"),
        KEY_C(99, "c"),
        KEY_D(100, "d"),
        KEY_E(101, "e"),
        KEY_F(102, "f"),
        KEY_G(103, "g"),
        KEY_H(104, "h"),
        KEY_I(105, "i"),
        KEY_J(106, "j"),
        KEY_K(107, "k"),
        KEY_L(108, "l"),
        KEY_M(109, "m"),
        KEY_N(110, "n"),
        KEY_O(111, "o"),
        KEY_P(112, "p"),
        KEY_Q(113, "q"),
        KEY_R(114, "r"),
        KEY_S(115, "s"),
        KEY_T(116, "t"),
        KEY_U(117, "u"),
        KEY_V(118, "v"),
        KEY_W(119, "w"),
        KEY_X(120, "x"),
        KEY_Y(121, "y"),
        KEY_Z(122, "z"),

        KEY_SHIFT(-1, "shift"),
        KEY_SPACE(32, "space"),
        KEY_SWITCH(-114, "switch"),
        KEY_DEL(-100, "del");

        private final int CODES;
        private final String LABEL;

        private int CODES() {
            return this.CODES;
        }

        private String LABEL() {
            return this.LABEL;
        }

        public static String getLabel(int code) {
            KEY_CODES[] keyCodes = values();
            for (KEY_CODES keyCode : keyCodes) {
                if (keyCode.CODES() == code) {
                    return keyCode.LABEL();
                }
            }
            return "UNKNOWN";
        }

        KEY_CODES(int CODES, String LABEL) {
            this.CODES = CODES;
            this.LABEL = LABEL;
        }
    }

    public void closeKeyboard() {
        mKeyboardView.setVisibility(View.GONE);
    }

    public boolean isKeyboardVisible() {
        return mKeyboardView.getVisibility() == View.VISIBLE;
    }
}
