package com.mvc.netty;

import com.mvc.model.upgrade.TUpgradeResultsModel;
import com.mvc.netty.dealconstant.UpgradeIdentifier;
import com.mvc.utils.NumberUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 版本报文解析器
 */
@Component
public class VersionMessageParser {
    private static Logger log = LoggerFactory.getLogger(VersionMessageParser.class);

    public TUpgradeResultsModel parse(String msg) {
        TUpgradeResultsModel resultsModel = new TUpgradeResultsModel();

        String temp = msg;
        List<String> keys = UpgradeIdentifier.keys();
        while (temp.length() > 0) {
            /** 是否匹配到元素 2024-03-26 guozhao
             * 调试发现如何设备上报的长度与实际不符或其它未知数据,在while中会导致死循环
             * 当发现未匹配到任务元素时,退出while循环,本次数据有异常
             * **/
            boolean isMatch = false;
            for (String key : keys) {
                if (temp.toUpperCase().startsWith(key)) {
                    isMatch = true;
                    UpgradeIdentifier identifier = UpgradeIdentifier.getElement(key);
                    if (identifier == null) continue;
                    String value = "";
                    temp = identifier.parse(temp);
                    value = identifier.getValue();

                    switch (identifier) {
                        case FF08:
                            resultsModel.setDeviceSn(value.length() > 11 ? value.substring(0, 11) : value);
                            break;
                        case FF16:
                            resultsModel.setVersionNum(value);
                            break;
                        case FF42:
                            resultsModel.setSoftwareName(NumberUtil.hexToAscii(value));
                            break;
                        case FF43:
                            resultsModel.setCheckType(Integer.valueOf(value));
                            break;
                        case FF44://不考虑先有校验2,再有校验1的可能
                            resultsModel.setCheckCode(value);
                            break;
                        case FF45://将校验2拼接到后面
                            resultsModel.setCheckCode((resultsModel.getCheckCode() + value).toUpperCase());
                            break;
                    }
                }
            }

            if (!isMatch) {
                //遍例后,未匹配到元素
                resultsModel = null;
                log.warn("ED 报文错误:" + msg);
                break;
            }
        }

        return resultsModel;
    }
}
