package api.common.util;

import lombok.SneakyThrows;
import org.gitlab4j.api.GitLabApi;
import org.gitlab4j.api.models.Commit;
import org.gitlab4j.api.models.Project;

import java.util.Date;
import java.util.List;

/**
 * <!-- https://mvnrepository.com/artifact/org.gitlab4j/gitlab4j-api -->
 * <dependency>
 * <groupId>org.gitlab4j</groupId>
 * <artifactId>gitlab4j-api</artifactId>
 * <version>5.0.1</version>
 * </dependency>
 */
public class GitLabUtil {

    /**
     * @param projectUrl git 仓库地址 http://gitlab-441-442-443/root/test1021.git
     * @param username
     * @param password
     * @return
     */
    @SneakyThrows
    public static long getLastCommitTimestamp(String projectUrl, String username, String password) {
        String[] split = projectUrl.split("/");
        String hostUrl = split[0] + "/" + split[1] + "/" + split[2];
        String projectName = split[4].split("\\.")[0];
        GitLabApi gitLabApi = GitLabApi.oauth2Login(hostUrl, username, password);
        Project project = gitLabApi.getProjectApi().getProject(username, projectName);
        Long projectId = project.getId();
        List<Commit> master = gitLabApi.getCommitsApi().getCommits(projectId, "master", new Date(1666331629),
                new Date(System.currentTimeMillis()));
        master.sort((commit1, commit2) -> commit2.getCommittedDate().compareTo(commit1.getCommittedDate()));    // 降序
        Commit commit = master.get(0);
        Date committedDate = commit.getCommittedDate();
        return committedDate.getTime();
    }
}
