package tech.glinfo.enbao.modules.infrared.util;


import tech.glinfo.enbao.common.utils.ByteUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ProtocolUtil {
    /**
     * 压缩数据
     * @param datas
     * @param frequency
     * @return
     */
    public static String getCmds(String[] datas, String frequency) {
        List<String> samples = new ArrayList<>();
        Map<String, String> samplesIndex = new HashMap<>();
        for (String code : datas) {
            if(!samplesIndex.containsKey(code)) {
                int i = new BigDecimal(Integer.valueOf(code) / 4).setScale(0, RoundingMode.HALF_UP).intValue();
                samples.add(ByteUtils.int2Hex(i, 4));
                samplesIndex.put(code, Integer.toHexString(samples.size()));
            }
        }
        while (samples.size()<16) {
            samples.add("0000");
        }
        //样版
//        StringBuffer samp = new StringBuffer("0324");
        StringBuffer samp = new StringBuffer();
        samp.append(ByteUtils.int2Hex(Integer.valueOf(frequency), 4));
        for (String s : samples) {
            samp.append(s);
        }
        int length1 = datas.length;
        if(length1%2 != 0) {
            length1++;
        }
        samp.append(ByteUtils.int2Hex(Integer.valueOf(length1), 4));
//        System.out.print(splitT(samp.toString()));

        //长度
        StringBuffer sbdata = new StringBuffer(samp);
        //循环查找数据所在位置
        for (String code : datas) {
            sbdata.append(samplesIndex.get(code));
        }
        int length = sbdata.length();

        if(length%2 != 0) {
            sbdata.append("0");
        }

        return sbdata.toString();
    }
}
