package org.jpos.util;

public class StringParsingUtil {
    static int LEN_S_TPDUID = 1;
    static int LEN_S_DESTINATIONADDRESS = 2;
    static int LEN_S_SOURCEADDRESS = 2;
    static int LEN_S_MESSAGEID = 2;
    static int LEN_S_PRIMARYBITMAP = 8;
    static byte[][] fieldsTable = new byte[65][2];

    public static byte[] str2bcd(String s, boolean padLeft, byte[] d, int offset) {
        int len = s.length();
        int start = (((len & 1) == 1) && padLeft) ? 1 : 0;
        for (int i = start; i < len + start; i++)
            d[offset + (i >> 1)] |= (s.charAt(i - start) - '0') << ((i & 1) == 1 ? 0 : 4);
        return d;
    }

    public static byte[] str2bcd(String s, boolean padLeft) {
        int len = s.length();
        byte[] d = new byte[(len + 1) >> 1];

        return str2bcd(s, padLeft, d, 0);
    }

    public static String hexString(byte[] b) {
        StringBuffer d = new StringBuffer(b.length * 2);
        for (int i = 0; i < b.length; i++) {
            char hi = Character.forDigit((b[i] >> 4) & 0x0F, 16);
            char lo = Character.forDigit(b[i] & 0x0F, 16);
            d.append(Character.toUpperCase(hi));
            d.append(Character.toUpperCase(lo));
        }
        return d.toString();
    }

    public static char[] addTwoArrays(byte[] array1, char[] array2) {

        char[] result = new char[array1.length + array2.length];

        for (int i = 0; i < array1.length; i++) {

            result[i] = (char) array1[i];

        }

        for (int i = array1.length; i < result.length; i++) {

            result[i] = array2[i - array1.length];

        }

        return result;


    }


    public static byte[] addTwobyteArray(byte[] array1, byte[] array2) {

        byte[] result = new byte[array1.length + array2.length];

        for (int i = 0; i < array1.length; i++) {
            result[i] = array1[i];
        }

        for (int i = array1.length; i < result.length; i++) {
            result[i] = array2[i - array1.length];
        }

        return result;


    }

    public static String maskCardNumber(String cardnumber) {
        int cardLen = cardnumber.length();
        if (cardLen > 10) {
            String c1 = cardnumber.substring(0, 6);
            String c2 = cardnumber.substring(cardLen - 4, cardLen);
            String c3 = cardnumber.substring(6, cardLen - 4);
            c3 = c3.replaceAll("[0-9]", "x");
            return (c1 + c3 + c2);
        }
        return cardnumber;
    }
}
