package io.trustbuilder.mfa.android.demoapp.utils;

import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.widget.EditText;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

public class PinEditable extends SpannableStringBuilder {
    public char[] getPin() {
        char[] pin = new char[length()];
        getChars(0, length(), pin, 0);
        clear();
        return pin;
    }

    @Override
    public String toString() {
        return "";
    }

    @Override
    public int hashCode() {
        return 0;
    }

    private static byte[] toBytes(char[] chars) {
        CharBuffer charBuffer = CharBuffer.wrap(chars);
        ByteBuffer byteBuffer = StandardCharsets.UTF_8.encode(charBuffer);
        byte[] bytes = Arrays.copyOfRange(byteBuffer.array(),
                byteBuffer.position(), byteBuffer.limit());
        Arrays.fill(byteBuffer.array(), (byte) 0); // clear sensitive data
        return bytes;
    }

    public static byte[] getBytesFromTextview(EditText textView) {
        Editable seq = textView.getText();
        char[] textValue = null;
        if (seq instanceof PinEditable) {
            textValue = ((PinEditable) seq).getPin();
        } else {
            textValue = new char[seq.length()];
            seq.getChars(0, seq.length(), textValue, 0);
        }
        textView.setText("");
        seq.clear();
        seq.clearSpans();
        byte[] bytes = toBytes(textValue);
        Arrays.fill(textValue, (char) 0);
        return bytes;
    }
}
