package ru.nbch.credit_tracker.config.settings.version;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.util.Properties;
import java.util.function.Function;

@Slf4j
public class VersionInfoProvider {

    public static String obtainVersionInfo(Properties properties, String prefix) {
        VersionInfoProvider gitVersionInfo = VersionInfoProvider.build(properties, prefix);
        if (gitVersionInfo != null) return gitVersionInfo.toString();
        log.warn("no build info is available by git-commit-id-plugin...");
        return "[UNKNOWN VERSION]";
    }

    public static VersionInfoProvider build(Properties properties, String prefix) {
        if (properties == null || prefix == null) return null;
        VersionInfoProvider provider = new VersionInfoProvider(properties, prefix);
        if (!StringUtils.hasText(provider.gitRevision)) return null;
        return provider;
    }


    //from git-commit-id-plugin
    private String gitRevision;
    private String gitBranch;
    private String mavenVersion;
    private String buildTime;
    private String tag;

    private VersionInfoProvider(Properties properties, String prefix) {
        Function<String, String> pref = s -> prefix + "." + s;
        if (properties != null) {
            gitRevision = properties.getProperty(pref.apply("commit.id"));
            gitBranch = properties.getProperty(pref.apply("branch"));
            mavenVersion = properties.getProperty(pref.apply("build.version")); //project version from maven
            buildTime = properties.getProperty(pref.apply("build.time"));
            tag = properties.getProperty(pref.apply("closest.tag.name"));
        }
    }

    @Override
    public String toString() {
        if (gitRevision != null) {
            return String.format("v. %s-%s-%s-%s", //-%s-%s
                    mavenVersion,
                    gitBranch,
                    gitRevision.substring(0, Math.min(gitRevision.length(), 8)),
                    buildTime //, tag, gitRevision
            );
        }  else {
            return "UNKNOWN_VERSION";
        }
    }
}
