package cn.reghao.bnt.web.devops.builder.tool.repo;

import org.eclipse.jgit.errors.UnsupportedCredentialItem;
import org.eclipse.jgit.transport.CredentialItem;
import org.eclipse.jgit.transport.CredentialsProvider;
import org.eclipse.jgit.transport.URIish;

/**
 * @author reghao
 * @date 2023-03-13 09:07:46
 */
public class CustomCredentialProvider extends CredentialsProvider {
    private final String passphrase;

    public CustomCredentialProvider(String passphrase) {
        // 私钥的访问密码(没有密码则传入 null)
        this.passphrase = passphrase;
    }

    @Override
    public boolean isInteractive() {
        // Set this according to your requirement
        return false;
    }

    @Override
    public boolean supports(CredentialItem... items) {
        // Set this according to your requirement
        return true;
    }

    @Override
    public boolean get(URIish uri, CredentialItem... items)
            throws UnsupportedCredentialItem {

        for (CredentialItem item : items) {
            if (item instanceof CredentialItem.InformationalMessage) {
                continue;
            }
            if (item instanceof CredentialItem.YesNoType) {
                // Set this according to your requirement
                ((CredentialItem.YesNoType) item).setValue(true);
            } else if (item instanceof CredentialItem.CharArrayType) {
                if (passphrase != null) {
                    ((CredentialItem.CharArrayType) item)
                            .setValue(passphrase.toCharArray());
                } else {
                    return false;
                }
            } else if (item instanceof CredentialItem.StringType) {
                if (passphrase != null) {
                    ((CredentialItem.StringType) item)
                            .setValue(passphrase);
                } else {
                    return false;
                }
            } else {
                return false;
            }
        }
        return true;
    }
}
