package com.pinelabs.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class DataUtils {
    public static String adjustPadding(String input, int blockSize) {

        int len = input.length() % blockSize;
        int paddingLength = (len == 0) ? 0 : (blockSize - len);

        while (paddingLength > 0) {
            input += "F";
            paddingLength--;
        }

        return input;
    }

    public static byte[]  adjustUnicodePadding(String input, int blockSize) throws IOException {
        byte[] inputByte = input.getBytes("UTF-8");
        int len = inputByte.length % blockSize;
        int paddingLength = (len == 0) ? 0 : (blockSize - len);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        baos.write(inputByte);
        while (paddingLength > 0) {
            baos.write("F".getBytes("UTF-8"));
            paddingLength--;
        }
        return baos.toByteArray();
    }


    public static String adjustPadding(String input) throws IOException {
        return adjustPadding(input, 8);
    }

    public static String getderEncodeDesKey(int keylength, String correctedDesKey) {
        String derEncodeDesKey;
        if (keylength == 112) {
            derEncodeDesKey = "30240410" + correctedDesKey + "041099999999999999999999999999999999";
        } else {
            derEncodeDesKey = "302C0418" + correctedDesKey + "041099999999999999999999999999999999";
        }
        return derEncodeDesKey;
    }

    public static String xorHex(String a, String b) {
        char[] chars = new char[a.length()];
        for (int i = 0; i < chars.length; i++) {
            chars[i] = toHex(fromHex(a.charAt(i)) ^ fromHex(b.charAt(i)));
        }
        return new String(chars).toUpperCase();
    }

    private static int fromHex(char c) {
        if ((c >= '0') && (c <= '9')) {
            return c - '0';
        }
        if ((c >= 'A') && (c <= 'F')) {
            return c - 'A' + 10;
        }
        if ((c >= 'a') && (c <= 'f')) {
            return c - 'a' + 10;
        }
        throw new IllegalArgumentException();
    }

    private static char toHex(int nybble) {
        if ((nybble < 0) || (nybble > 15)) {
            throw new IllegalArgumentException();
        }
        return "0123456789ABCDEF".charAt(nybble);
    }

    public static String formatTheResponse(String clearData) {
        try {
            clearData=clearData.substring(clearData.indexOf("{"),clearData.lastIndexOf("}")+1);
            return clearData;
        } catch (Exception e) {
            return clearData;
        }
    }

}
