/*
 * Copyright (C) 2025  Tim Zimmermann <tim@aglais.org>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.aglais.zms.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
import java.util.Properties;

/**
 * VersionUtil provides utility methods for working with version information.
 * It includes methods to retrieve the implementation version of the package
 * and to determine if a given version represents a development build.
 */
public class VersionUtil {

    private static final String LOG_TAG = VersionUtil.class.getSimpleName();

    /**
     * Returns the implementation version of this class's package.
     * If the version is not available, returns "DEV".
     *
     * @return The implementation version or "DEV" if not available
     */
    public static String getVersion() {
        String version = VersionUtil.class.getPackage().getImplementationVersion();

        return version != null ? version : "DEV";
    }

    /**
     * Retrieves the Git branch information from the git.properties file.
     *
     * @return The Git branch name as a String if found, otherwise returns an empty String
     */
    public static String getGitBranch() {
        Properties properties = new Properties();
        try (InputStream propertiesIn = VersionUtil.class.getResourceAsStream("/git.properties")) {
            if (propertiesIn != null) {
                properties.load(propertiesIn);

                return properties.getProperty("git.branch");
            } else {
                Log.w(LOG_TAG, "git.properties not found");
            }
        } catch (IOException e) {
            Log.e(LOG_TAG, "Failed to read git.properties", e);
        }

        return "";
    }

    /**
     * Checks if the given version string represents a development build.
     * A version is considered a development build if it is "DEV" or contains "SNAPSHOT".
     *
     * @param version The version string to check
     * @return true if the version is a development build, false otherwise
     */
    public static boolean isDevBuild(String version) {
        return "DEV".equalsIgnoreCase(version) || version.toUpperCase(Locale.ROOT).contains("SNAPSHOT");
    }
}