package com.onsemi.middleware.camel.karavan;

import com.onsemi.middleware.camel.context.GitLabKaravanSourceLoader;
import org.gitlab4j.api.GitLabApi;
import org.gitlab4j.api.GitLabApiException
import org.gitlab4j.api.RepositoryApi
import org.gitlab4j.api.models.Project
import org.gitlab4j.api.models.RepositoryFile
import org.gitlab4j.api.models.TreeItem;
import org.slf4j.Logger;
import spock.lang.Specification;
import spock.lang.Subject;

import java.nio.file.Files;
import java.nio.file.Path

class GitlabKaravanSourceLoaderTest extends Specification {

    @Subject
    GitLabKaravanSourceLoader loader = Spy()

    def setup() {
        loader = new GitLabKaravanSourceLoader()
    }

    def "Empty folder, log warning and skip downloading"() {
        given:
        String interfaceName = "TestInterface"
        String targetPath = Files.createTempDirectory("testDir").toString()

        when:
        loader.loadFolder(interfaceName, targetPath)

        then:
        0 * loader.downloadAndSaveFiles(_, _, _, _)

        cleanup:
        Files.deleteIfExists(Path.of(targetPath))
    }

    def "loadFolder should download files while folder is found"() {
        given:
        String interfaceName = "TestInterface"
        String targetPath = Files.createTempDirectory("testDir").toString()
        GitLabApi api = Mock(GitLabApi)
        RepositoryApi repositoryApi = Mock(RepositoryApi)
        api.getRepositoryApi() >> repositoryApi
        def loader2 = Spy(GitLabKaravanSourceLoader);
        loader2.initGitLabApi() >> api
        repositoryApi.getTree(_,_,_,false) >> [Mock(TreeItem)].toList()

        when:
        loader2.loadFolder(interfaceName, targetPath)

        then:
        1 * loader.downloadAndSaveFiles(_, _, _, _)
    }
}
