package com.atlassian.bitbucket.scm.cache.internal;

import com.atlassian.bitbucket.scm.cache.ScmCacheConfig;
import com.atlassian.bitbucket.scm.cache.ScmCacheService;
import com.atlassian.bitbucket.scm.cache.ScmRequestProtocol;
import com.atlassian.bitbucket.scm.cache.ScmRequestType;
import com.atlassian.support.tools.spi.RootLevelSupportInfoAppender;
import com.atlassian.support.tools.spi.SupportInfoBuilder;
import com.atlassian.util.contentcache.CacheStatistics;

/**
 * Provides support info about scm-cache to STP
 */
public class ScmCacheSupportInfo extends RootLevelSupportInfoAppender {

    private final ScmCacheService cacheService;
    private final ScmCacheConfig config;

    public ScmCacheSupportInfo(ScmCacheService cacheService, ScmCacheConfig config) {
        this.cacheService = cacheService;
        this.config = config;
    }

    @Override
    protected void addSupportInfo(SupportInfoBuilder rootBuilder) {
        SupportInfoBuilder builder = rootBuilder.addCategory(I18nKeys.STP_SECTION);
        builder.addValue(I18nKeys.STP_PROTOCOL_HTTP_ENABLED, Boolean.toString(config.isEnabled(ScmRequestProtocol.HTTP)));
        builder.addValue(I18nKeys.STP_PROTOCOL_SSH_ENABLED, Boolean.toString(config.isEnabled(ScmRequestProtocol.SSH)));

        SupportInfoBuilder refsBuilder = builder.addCategory(I18nKeys.STP_REF_ADVERTISEMENT);
        refsBuilder.addValue(I18nKeys.STP_ENABLED, Boolean.toString(config.isEnabled(ScmRequestType.REFS)));
        refsBuilder.addValue(I18nKeys.STP_TTL, Long.toString(config.getTimeToLive(ScmRequestType.REFS)));

        SupportInfoBuilder uploadPackBuilder = builder.addCategory(I18nKeys.STP_UPLOAD_PACK);
        uploadPackBuilder.addValue(I18nKeys.STP_ENABLED, Boolean.toString(config.isEnabled(ScmRequestType.UPLOAD_PACK)));
        uploadPackBuilder.addValue(I18nKeys.STP_TTL, Long.toString(config.getTimeToLive(ScmRequestType.UPLOAD_PACK)));

        // add statistics section
        SupportInfoBuilder statsBuilder = builder.addCategory(I18nKeys.STP_STATISTICS_SECTION);
        CacheStatistics statistics = cacheService.getStatistics();
        statsBuilder.addValue(I18nKeys.STP_STATISTICS_HITS, Long.toString(statistics.getHits()));
        statsBuilder.addValue(I18nKeys.STP_STATISTICS_MISSES, Long.toString(statistics.getMisses()));
        statsBuilder.addValue(I18nKeys.STP_STATISTICS_SIZE, Long.toString(statistics.getSize()));
    }
}
