package info.knacki.pass.ui.alertPrompt.views;

import android.content.Context;
import android.inputmethodservice.KeyboardView;
import android.support.v7.widget.AppCompatEditText;
import android.text.Editable;
import android.widget.LinearLayout;

import info.knacki.pass.ui.alertPrompt.integratedKeyboard.KeyboardWidget;

public class SimpleTextEditWithKeyboard  extends LinearLayout implements KeyboardWidget.OnKeyListener {
    protected final AppCompatEditText fTextEdit;

    public SimpleTextEditWithKeyboard(Context c) {
        super(c);
        fTextEdit = new SimpleTextEdit(c);
        fTextEdit.setFocusable(false);
        addView(fTextEdit);
        KeyboardView keyboard = new KeyboardWidget(c).SetListener(this);
        addView(keyboard);
        setOrientation(VERTICAL);
    }

    public SimpleTextEditWithKeyboard setText(String str) {
        fTextEdit.setText(str);
        fTextEdit.setSelection(str.length());
        return this;
    }

    public String getStr() {
        Editable text = fTextEdit.getText();
        return null == text ? "" : text.toString().trim();
    }

    @Override
    public void OnKeyReceived(CharSequence c) {
        final int selectionStart = fTextEdit.getSelectionStart();
        final int selectionEnd = fTextEdit.getSelectionEnd();

        Editable text = fTextEdit.getText();
        if (null != text)
            text.replace(selectionStart, selectionEnd, c);
    }

    public void OnBackspace() {
        final int selectionEnd = fTextEdit.getSelectionEnd();
        final int selectionStart = Math.max(0, fTextEdit.getSelectionStart() == selectionEnd ? fTextEdit.getSelectionStart() - 1 : fTextEdit.getSelectionStart());

        Editable text = fTextEdit.getText();
        if (null != text)
            text.replace(selectionStart, selectionEnd, "");
    }
}
