package com.cisdi.data.HJ212.gateway;

import java.nio.charset.StandardCharsets;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Hj212VoEncoder {
    private static DateFormat qnFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
    
    public static byte[] encode(String st, String cn, String pw, String mn) {
        String flag = "4";
        
        String asciiString = combineAsciiString(null, st, cn, pw, mn, flag);

        return asciiString.getBytes(StandardCharsets.US_ASCII);
    }

    private static String combineAsciiString(String qn, String st, String cn, String pw, String mn, String flag) {
        Date date = new Date();
        StringBuilder builder = new StringBuilder();
        builder.append(String.format("QN=%s;", qn == null ? qnFormat.format(date) : qn));
        builder.append(String.format("ST=%s;", st));
        builder.append(String.format("CN=%s;", cn));
        builder.append(String.format("PW=%s;", pw));
        builder.append(String.format("MN=%s;", mn));
        builder.append(String.format("Flag=%s;", flag));
        builder.append("CP=&&&&");
        
        String dataBody = builder.toString();
        int dataLength = builder.toString().length();
        
        builder.insert(0, String.format("##%04d", dataLength));
        String crc16 = CRC16Util.CRC16(dataBody);
        builder.append(crc16 + "\r\n");
        
        return builder.toString();
    }
    
    public static void main(String[] args) {
        String combine1 = combineAsciiString("20190425110917290", "22", "9014", "123456", "01004190001003", "4");
        System.out.println(combine1);
        
        String combine2 = combineAsciiString("20190425110913469", "22", "9014", "123456", "0100410001003", "4");
        System.out.println(combine2);
    }
}