import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import tech.glinfo.enbao.common.utils.StringUtils;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.spec.AlgorithmParameterSpec;

public class StringTest {
    public static void main(String[] args) {
//        String sessionKey = "JocQqerjzSbHxUAAH5sgeA==";
//        String encryptedData = "LNHylEIMCHE+6YpbaxyC69fmb7zWCcM8PSUE+V25JQn5QEdcyyji6/4EcnkXnNiwYeOgGacBZwQrYApGvhCUgh5quSMCXBpUavPCWdFosU89j1jWAWh8UC7wHUBqO83hipEDuRfKgcvHoQPj7dhmrHZ+9AguPvrs5NlGIR4eFuHOR81Y1o0WgK6PV2VV0OmYnAqqETls3SH1pg+PNfqml2bGPKHM5eM8w/6qPoVrmLIKPo6uAFTfAUX+Ca1kBzpZabJqqEloHaa4I6rs5gVxG+tt2HtwTo7rPpjLNIzjfnGiVE7KzLv/EJ+aVx5WTQLQvqEWqoVYnUFMqvu8qb8zOmOsnyHdKzaSAT/wWqI3cpww8ZA3JWBob+nQztBMU5AUwDxsNivD/1ePx2f6MZYnWZKethUdrZla6wiaBRzm1aEuWwHXHdsfhWTu3pHTK5vpcQYXIyfhG2YycmrALxHoquFKajacwxD9oGk0+bBDZASNmqte9GTB4htkE4zjjcv4B/mC1mLLQo7mUTDaayRAqg==";
//        String iv = "2FMgfMUw/GeHKp1VjYdwZQ==";
//        JSONObject jsonObject = decode(sessionKey, encryptedData, iv);
//        System.out.println(jsonObject);


        String ssid = "TP-LINK_932D中";
        String _pwd = "gl123456#";

        //03AB78550C54502D4C494E4B5F3933324409676C3132333435362306FB
        //03AB78550C54502D4C494E4B5F3933324409676C3132333435362306FB
        //03AB78550C54502D4C494E4B5F3933324409676C3132333435362306FB
        //03AB78550F54502D4C494E4B5F39333244
        // E4B8AD
        // 09676C313233343536230947
        //03AB78550E54502D4C494E4B5F39333244
        // 4E2D
        // 09676C313233343536230778

        //03AB78550F54502D4C494E4B5F39333244E4B8AD09676C313233343536230947
        //03AB78550F54502D4C494E4B5F39333244E4B8AD09676C313233343536230947
        //03AB78550F54502D4C494E4B5F39333244E4B8AD09676C313233343536230947

        StringBuffer info = new StringBuffer("03AB7855");
//        String wifi = strToHex(ssid);
//        String pwd = strToHex(_pwd);
        String wifi = bytes2HexString(getBytesByString(ssid));
        System.out.println(wifi);
        System.out.println(bytes2HexString(getBytesByString("TP-LINK_932D")));
        String pwd = bytes2HexString(getBytesByString(_pwd));

        info.append(int2Hex(wifi.length()/2));
        info.append(wifi);
        info.append(int2Hex(pwd.length()/2));
        info.append(pwd);
        info.append(makeCheckNum(info.toString()));
//        Log.e("INFO",info.toString());
        //THE INTERNET OF EVERYTHING BEGINS HERE

        System.out.println(info);


        byte[] bytes = hexStrToBinaryStr(info.toString());
        for (byte b : bytes) {
            System.out.print(Integer.valueOf(b));
        }

    }

    public static byte[] hexStrToBinaryStr(String hexString) {
        hexString = hexString.replaceAll(" ", "");
        int len = hexString.length();
        int index = 0;
        byte[] bytes = new byte[len / 2];
        while (index < len) {
            String sub = hexString.substring(index, index + 2);
            bytes[index / 2] = (byte) Integer.parseInt(sub, 16);
            index += 2;
        }
        return bytes;
    }

    public static String strToHex(String s) {
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            int ch = (int) s.charAt(i);
            String s4 = Integer.toHexString(ch);
            str.append(s4);
        }
        return str.toString().toUpperCase();
    }


    private static String intToHex(int n) {
        //StringBuffer s = new StringBuffer();
        StringBuilder sb = new StringBuilder(8);
        String a;
        char[] b = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        while (n != 0) {
            sb = sb.append(b[n % 16]);
            n = n / 16;
        }
        a = sb.reverse().toString();
        return a;
    }

    public static String int2Hex(int n) {
        if(n == 0) {
            return "00";
        }
        String s = intToHex(n);
        int i = s.length() % 2;
        StringBuilder sb = new StringBuilder();
        while (i > 0) {
            sb.append("0");
            i--;
        }

        return sb.append(s).toString();
    }

    public static String makeCheckNum(String data) {
        if (data == null || data.equals("")) {
            return "";
        }
        int total = 0;
        int len = data.length();
        int num = 0;
        while (num < len) {
            String s = data.substring(num, num + 2);
            total += Integer.parseInt(s, 16);
            num = num + 2;
        }
        return int2Hex(total);
    }

    public static String bytes2HexString(byte[] bArray) {
        StringBuffer sb = new StringBuffer(bArray.length);
        String sTemp;
        for (int i = 0; i < bArray.length; i++) {
            sTemp = Integer.toHexString(0xFF & bArray[i]);
            if (sTemp.length() < 2) {
                sb.append(0);
            }
            sb.append(sTemp.toUpperCase());
        }
        return sb.toString();
    }

    public static byte[] getBytesByString(String string) {
        try {
            return string.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new IllegalArgumentException("the charset is invalid");
        }
    }

    private static JSONObject decode(String sessionKey, String encryptedData, String iv) {
        byte[] encrypData = Base64.decodeBase64(encryptedData);
        byte[] ivData = Base64.decodeBase64(iv);
        byte[] sessionKeyB = Base64.decodeBase64(sessionKey);
        Security.addProvider(new BouncyCastleProvider());
        AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivData);
        byte[] doFinal = new byte[0];
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding","BC");
            SecretKeySpec keySpec = new SecretKeySpec(sessionKeyB, "AES");
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            doFinal = cipher.doFinal(encrypData);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        if(doFinal != null && doFinal.length > 0) {
            String result = new String(doFinal);
            System.out.println(result);
            return JSONObject.parseObject(result);
        }

        return new JSONObject();
    }

}
