package net.northking.cctp.scriptcase.api.scenescript.service.verfiy;

import net.northking.cctp.common.exception.PlatformRuntimeException;
import net.northking.cctp.scriptcase.api.scenescript.bean.Node;
import net.northking.cctp.scriptcase.api.scenescript.bean.SceneScript;
import net.northking.cctp.scriptcase.enums.ErrorMessage;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class SceneNodeNameVerify  implements IDataVerify<SceneScript> {
    @Override
    public boolean verify(SceneScript dataDto) throws Exception{//同个场景明，节点名唯一校验
        if(dataDto.nodes == null || dataDto.nodes.size() == 0)
            throw new PlatformRuntimeException(new ErrorMessage("场景节点数为空"));

        //开始，结束节点检验;节点重名校验
        Map<String, Integer> nameCountMap = new HashMap<>();
        for (int i=0; i < dataDto.nodes.size(); i++){
            Node n = dataDto.nodes.get(i);
            String nodeName = n.nodeName;
            if(StringUtils.isEmpty(n.nodeName))
                throw new PlatformRuntimeException(new ErrorMessage("节点名称不能为空"));
            if(!nameCountMap.containsKey(nodeName))
                nameCountMap.put(nodeName, 1);
            else
                nameCountMap.put(nodeName, nameCountMap.get(nodeName) + 1) ;
        }
        StringBuilder sb = new StringBuilder();
        for(Map.Entry<String, Integer> kv : nameCountMap.entrySet()){
            if(kv.getValue() > 1)
                sb.append(kv.getKey()).append(",");
        }
        String dupName = sb.toString();
        if(StringUtils.hasText(dupName)) {
            dupName = dupName.substring(0, dupName.length() - 1);
            throw new PlatformRuntimeException(new ErrorMessage("节点名称重复(" + dupName + ")"));
        }

        return true;
    }
}
