package api.common.util;

import lombok.SneakyThrows;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;

import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;



/**
 <dependency>
 <groupId>org.eclipse.jgit</groupId>
 <artifactId>org.eclipse.jgit</artifactId>
 </dependency>
 */
public class JgitUtil {


    public static Map<String, Ref> testConnection(String remoteUrl, String username, String password) {
        try {
            return testPublicConnection(remoteUrl);
        } catch (Exception e) {
            try {
                return testPrivateConnection(remoteUrl,username,password);
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    }



    public static Map<String, Ref> testPrivateConnection(String remoteUrl, String username, String password) {
        try {
            UsernamePasswordCredentialsProvider provider = new UsernamePasswordCredentialsProvider(username,password);
            return Git.lsRemoteRepository().setRemote(remoteUrl).setCredentialsProvider(provider).callAsMap();
        } catch (GitAPIException e) {
            throw new RuntimeException(e);
        }
    }

    public static Map<String, Ref> testPublicConnection(String remoteUrl) {
        try {
            return Git.lsRemoteRepository().setRemote(remoteUrl).callAsMap();
        } catch (GitAPIException e) {
            throw new RuntimeException("私有仓库需输入用户名密码，请检查。");
        }
    }

    public static Map<String, Ref> testConnectionByToken(String remoteUrl, String gitToken) throws GitAPIException {
        UsernamePasswordCredentialsProvider provider = new UsernamePasswordCredentialsProvider("PRIVATE-TOKEN", gitToken);
        Map<String, Ref> asMap = Git.lsRemoteRepository().setRemote(remoteUrl).setCredentialsProvider(provider).callAsMap();
        return asMap;
    }

    public static Git clone(String remoteUrl, String directory, String username, String password) throws GitAPIException, IOException {
        UsernamePasswordCredentialsProvider provider = new UsernamePasswordCredentialsProvider(username,password);
        File localPath = new File(directory);
        Git result = Git.cloneRepository().setURI(remoteUrl).setDirectory(localPath).setCredentialsProvider(provider).call();
        return result;
    }

    @SneakyThrows
    public static long getLastCommitTimestamp(String url, String username, String password, String directory) {
        Git git = Git.cloneRepository()
                .setURI(url)
                .setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password))
                .setDirectory(new File(directory))
                .call();
        Iterable<RevCommit> logIterable = git.log().call();
        Iterator<RevCommit> logIterator = logIterable.iterator();//获取所有版本号的迭代器
        if (!logIterator.hasNext()) {
            throw new RuntimeException("GitUtil.getLastCommitTimestamp() git 仓库 " + url + " 没有提交过数据。");
        }

        Date lastCommitDate = new Timestamp(1666331629);
        int i = 0;
        while (logIterator.hasNext()) {
            RevCommit commit = logIterator.next();
            Date commitDate = commit.getAuthorIdent().getWhen();     //提交时间
            if (i == 0) {
                lastCommitDate = commitDate;
            } else {
                if (commitDate.compareTo(lastCommitDate) > 0) {
                    lastCommitDate = commitDate;
                }
            }
            i++;
        }
        git.close();
        FileUtil.rm(directory);
        return TimeUtil.dateToTimestamp(lastCommitDate);
    }


//    public static void main(String[] args) throws GitAPIException, IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
//       try {
//           Git git = clone("https://github.com/tensorflow/serving.git","E:\\simulation-cloud\\test","","");
////           Iterable<RevCommit> iterable = git.log().call();
////           for (RevCommit u : iterable) {
////               String ID = String.valueOf(u.getId());
////               System.out.println("cgfghdnhg");
////               System.out.println(u.getFullMessage());
////               System.out.println( ID);
////               System.out.println("done!!");
//////               正则表达式 截取需要的部分
//////               versionID = getMatcher("commit\\s(\\w+)\\s?", ID);
////               break;
////           }
//           System.out.println("slfasjkfasfksd:");
//           System.out.println(git.log());
//       }catch (Exception e){
//           System.out.println("failllll:");
//       }
//    }




}
