/*
 * Copyright (c) 2021 LG Electronics Inc.
 * SPDX-License-Identifier: AGPL-3.0-only 
 */

package oss.fosslight.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import oss.fosslight.repository.ApiVulnerabilityMapper;
import oss.fosslight.service.ApiOssService;
import oss.fosslight.service.ApiVulnerabilityService;
import oss.fosslight.util.StringUtil;

@Service
public class ApiVulnerabilityServiceImpl implements ApiVulnerabilityService {
	/** The api oss mapper. */
	@Autowired Environment env;
	@Autowired ApiVulnerabilityMapper apiVulnerabilityMapper;
	@Autowired ApiOssService apiOssService;
	
	public List<Map<String, Object>> selectNvdList(String product, String version, String id){
		Map<String, Object> paramMap = new HashMap<String, Object>();
		String[] nicknameList = apiOssService.getOssNickNameListByOssName(product);
		
		paramMap.put("ossName", product);
		paramMap.put("ossVersion", version);
		paramMap.put("cveId", id);
		paramMap.put("ossNicknames", nicknameList);
		
		if (!StringUtil.isEmpty(product) && product.contains(" ")) {
			paramMap.put("underbarOssName", product.replaceAll(" ", "_"));
		}
		
		List<Map<String, Object>> nvdList = apiVulnerabilityMapper.selectNvdList(paramMap);
		List<String> duplicatedStr = new ArrayList<String>();
		List<Map<String, Object>> duplicatedNvdList = new ArrayList<Map<String, Object>>();
		
		for (Map<String, Object> nvd : nvdList) {
			String s = (String) nvd.get("cveId");
			if (!duplicatedStr.contains(s)) {
				duplicatedStr.add(s);
				duplicatedNvdList.add(nvd);
			}
		}
		return duplicatedNvdList;
	}
	
	public List<Map<String, Object>> selectMaxScoreNvdInfo(String product, String version){
		Map<String, Object> paramMap = new HashMap<String, Object>();
		
		paramMap.put("ossName", product);
		paramMap.put("ossVersion", version);
		paramMap.put("host", env.getProperty("server.domain"));
		
		if (product.contains(" ")) {
			paramMap.put("underbarOssName", product.replaceAll(" ", "_"));
		}
		
		return apiVulnerabilityMapper.selectMaxScoreNvdInfo(paramMap);
	}
}
