/*
 * Copyright 2017, The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cgmblelib.database;


import androidx.annotation.NonNull;
import androidx.room.TypeConverter;

/**
 * 字节转换
 * 数据库中将byte 转换成String 类型存储，读取时将String转换成byte
 * @author minyuchun
 */
public class ByteConverter {
    @TypeConverter
    public static byte[] toByte(String bytes) {
        return bytes == null ? null : strs16ToByteArray(bytes);
    }

    @TypeConverter
    public static String toStr(byte[] bytes) {
        return bytes == null ? null : byteArrayToStrs16(bytes);
    }

    private static byte[] strs16ToByteArray(@NonNull String strs16){
        String newStr = strs16.trim();
        if (newStr.length() > 0){
            String[] strs = strs16.split("\\s");
            byte[] bytes = new byte[strs.length];
            for (int i=0 ; i < bytes.length ; i++){
                bytes[i] = str16ToByte(strs[i]);
            }
            return bytes;
        }else {
            return new byte[0];
        }
    }

    private static byte str16ToByte(@NonNull String str16){
        byte b = 0;
        if (str16.length() > 0 && str16.length() < 3){
            char[] chars = str16.toCharArray();
            for (int j = 1; j<= chars.length; j++){
                b = (byte) (chartoByte(chars[j-1]) << (chars.length - j) * 4 | b);
            }
        }
        return b;
    }

    /***
     * 16进制字符类型转byte
     * @param c 16进制字符类型
     * @return byte 2进制
     */
    private static byte chartoByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    /**
     * 将 byte类型数组 转换成 16进制String类型字符串
     * @param bytes
     * @return
     */
    private static String byteArrayToStrs16(byte[] bytes){
        StringBuilder stringBuilder = new StringBuilder();
        for (byte b:bytes){
            stringBuilder.append(" ").append(byteToStr16(b));
        }
        return stringBuilder.substring(1).toUpperCase();
    }

    /**
     * 将 byte类型转换成 16进制String类型
     * @param b byte数据
     * @return 16进制String 类型
     */
    private static String byteToStr16(byte b){
        return Integer.toHexString(b & 0xff).length()==1?"0"+ Integer.toHexString(b & 0xff): Integer.toHexString(b & 0xff);
    }

}
