package net.northking.cctp.element.internal.utils;

import jodd.util.StringUtil;
import net.northking.cctp.element.internal.dto.FieldDto;

import java.nio.charset.Charset;
import java.util.List;

/**
 * 进制操作
 *
 * @author fengxiang.zhang
 * @since 1.0
 */
public class BinaryUtils {

    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | (charToByte(hexChars[pos + 1])) & 0xff );
        }
        return d;
    }

    public static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    public static String bytesToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            sb.append(String.format("%02X", bytes[i]));
        }
        return sb.toString();
    }

    public static String hexStrToString(String hexStr, String charset) {
        byte[] bytes = hexStringToBytes(hexStr);
        return bytes == null ? "" : new String(bytes, Charset.forName(charset));
    }

    public static void setHeaderLength(List<FieldDto> fieldDtos, StringBuilder result){
        for (int i = 0; i < fieldDtos.size(); i++) {
            FieldDto fieldDto =  fieldDtos.get(i);
            if(fieldDto.getChildrenColumn()!=null&&fieldDto.getChildrenColumn().size()>0){
                setHeaderLength(fieldDto.getChildrenColumn(),result);
            }
            String value = fieldDto.getDefaultValue();
            if(fieldDto.getColumnLength()!=null&&fieldDto.getColumnLength()>0
                    &&StringUtil.isNotBlank(fieldDto.getFillRule())){
                //拼接字段规则
                switch(fieldDto.getFillRule()){
                    case "0":
                        //0:左补0
                        value = MessageOperation.leftPad(value,fieldDto.getColumnLength(),"0");
                        break;
                    case "1":
                        //1:右补0
                        value = MessageOperation.rightPad(value,fieldDto.getColumnLength(),"0");
                        break;
                    case "2":
                        //2:左补空格
                        value = MessageOperation.leftPad(value,fieldDto.getColumnLength()," ");
                        break;
                    case "3":
                        //3:右补空格
                        value = MessageOperation.rightPad(value,fieldDto.getColumnLength()," ");
                        break;
                    default:
                        break;
                }
            }
            result.append(value);
        }
    }
}