/*
 * Copyright (c) 2023 - 2024. KeyWare.Co.Ltd All rights reserved.
 * 项目名称：Java 信息安全性设计准则
 * 项目描述：用于检查Java源代码的安全性设计准则的Sonarqube插件
 * 版权说明：本软件属北京关键科技股份有限公司所有，在未获得北京关键科技股份有限公司正式授权情况下，任何企业和个人，不能获取、阅读、安装、传播本软件涉及的任何受知识产权保护的内容。
 */
package com.keyware.sonar.java.rules;

import org.sonar.api.SonarEdition;
import org.sonar.api.SonarProduct;
import org.sonar.api.SonarQubeSide;
import org.sonar.api.SonarRuntime;
import org.sonar.api.server.rule.RulesDefinition;
import org.sonar.api.utils.Version;
import org.sonarsource.analyzer.commons.RuleMetadataLoader;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Objects;
import java.util.Set;

/**
 * 用于定义出现在规则页面中规则的元数据
 *
 * @author GuoXin
 * @date 2024/1/6
 */
public class JavaSecurityDesignRulesRepository implements RulesDefinition {
    // 不要修改这个值，因为路径在 CheckVerifier 中是硬编码的
    private static final String RESOURCE_BASE_PATH = "org/sonar/l10n/java/rules/java";

    public static final String REPOSITORY_KEY = "keyware-java-security-design";
    public static final String REPOSITORY_NAME = "Java安全性设计准则";

    // 添加需要视为模板规则的规则的规则键
    private static final Set<String> RULE_TEMPLATES_KEY = Collections.emptySet();

    private final SonarRuntime runtime;

    public JavaSecurityDesignRulesRepository(SonarRuntime runtime) {
        this.runtime = runtime;
    }

    @Override
    public void define(RulesDefinition.Context context) {
        RulesDefinition.NewRepository repository = context.createRepository(REPOSITORY_KEY, "java").setName(REPOSITORY_NAME);

        RuleMetadataLoader ruleMetadataLoader = new RuleMetadataLoader(RESOURCE_BASE_PATH, runtime);

        ruleMetadataLoader.addRulesByAnnotatedClass(repository, new ArrayList<>(RulesList.getChecks()));

        setTemplates(repository);

        repository.done();
    }

    private static void setTemplates(RulesDefinition.NewRepository repository) {
        RULE_TEMPLATES_KEY.stream()
                .map(repository::rule)
                .filter(Objects::nonNull)
                .forEach(rule -> rule.setTemplate(true));
    }


    public static class MockedSonarRuntime implements SonarRuntime {

        @Override
        public Version getApiVersion() {
            return Version.create(9, 9);
        }

        @Override
        public SonarProduct getProduct() {
            return SonarProduct.SONARQUBE;
        }

        @Override
        public SonarQubeSide getSonarQubeSide() {
            return SonarQubeSide.SCANNER;
        }

        @Override
        public SonarEdition getEdition() {
            return SonarEdition.COMMUNITY;
        }
    }
}
