package de.hftstuttgart.utils;

import de.hftstuttgart.config.ModocotProperties;
import io.gitea.ApiClient;
import io.gitea.ApiException;
import io.gitea.Configuration;
import io.gitea.api.RepositoryApi;
import io.gitea.api.UserApi;
import io.gitea.auth.HttpBasicAuth;
import io.gitea.model.CreateRepoOption;
import io.gitea.model.Repository;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;

@Component
public class GitTeaUtil {

    private static final Logger LOG = LogManager.getLogger(GitTeaUtil.class);

    private final ModocotProperties modocotProperties;

    public GitTeaUtil(ModocotProperties modocotProperties) {
        this.modocotProperties = modocotProperties;
    }

    /**
     * Create Git-Repository with name {@code repositoryName} on internal Git-Server
     *
     * @param repositoryName name of new Repository
     * @return newly created Repository
     */
    public Repository createRepository(String repositoryName) {
        setupAuth();
        Repository repo = null;
        try {
            repo = new UserApi()
                    .createCurrentUserRepo(new CreateRepoOption().name(repositoryName));
        } catch (ApiException e) {
            LOG.error(String.format("Error while creating repository: %s", repositoryName), e);
        }
        if (repo != null) {
            LOG.info("Created repository {} on {}", repositoryName, repo.getCloneUrl());
        } else {
            throw new IllegalStateException("Repository is null");
        }
        return repo;
    }

    /**
     * Delete Git-Repository with name {@code repositoryName} on internal Git-Server
     *
     * @param repositoryName name of new Repository
     */
    public void deleteRepository(String repositoryName) {
        setupAuth();
        try {
            new RepositoryApi().repoDelete(this.modocotProperties.getGitTeaUsername(), repositoryName);
        } catch (ApiException e) {
            LOG.error("Error while deleting repository:" + e.getMessage());
        }
    }

    /**
     * Check if a Git-Repository with the given name exists.
     *
     * @param repositoryName name of the Repository
     */
    public boolean repositoryExists(String repositoryName) {
        setupAuth();
        Repository repository = null;
        try {
            repository = new RepositoryApi().repoGet(this.modocotProperties.getGitTeaUsername(), repositoryName);
        } catch (ApiException e) {
            LOG.error("Error while deleting repository:" + e.getMessage());
        }
        return repository != null;
    }

    private void setupAuth() {
        ApiClient defaultClient = Configuration.getDefaultApiClient();

        defaultClient.setBasePath(this.modocotProperties.getGitTeaBasePath());
        HttpBasicAuth basicAuth = (HttpBasicAuth) defaultClient.getAuthentication("BasicAuth");
        basicAuth.setUsername(this.modocotProperties.getGitTeaUsername());
        basicAuth.setPassword(this.modocotProperties.getGitTeaPassword());
    }
}
