package com.tw.go.plugin.maven.apimpl;

import com.thoughtworks.go.plugin.api.logging.Logger;
import com.thoughtworks.go.plugin.api.material.packagerepository.PackageConfigurations;
import com.thoughtworks.go.plugin.api.material.packagerepository.PackageRepositoryPoller;
import com.thoughtworks.go.plugin.api.material.packagerepository.PackageRevision;
import com.thoughtworks.go.plugin.api.response.OperationResponse;
import com.thoughtworks.go.plugin.api.response.validation.Errors;
import com.thoughtworks.go.plugin.api.response.validation.ValidationError;
import com.tw.go.plugin.maven.LookupParams;
import com.tw.go.plugin.maven.client.MavenRepositoryClient;
import com.tw.go.plugin.maven.client.RepositoryConnector;
import com.tw.go.plugin.maven.client.Version;
import com.tw.go.plugin.maven.config.MavenPackageConfig;
import com.tw.go.plugin.maven.config.MavenRepoConfig;
import com.tw.go.plugin.util.RepoUrl;

import static com.tw.go.plugin.maven.config.MavenPackageConfig.ARTIFACT_ID;
import static com.tw.go.plugin.maven.config.MavenPackageConfig.GROUP_ID;

public class PollerImpl implements PackageRepositoryPoller {
    private static Logger LOGGER = Logger.getLoggerFor(PollerImpl.class);

    public PackageRevision getLatestRevision(PackageConfigurations packageConfig, PackageConfigurations repoConfig) {
        LOGGER.info(String.format("getLatestRevision called with groupId %s, artifactId %s, for repo: %s",
                packageConfig.get(GROUP_ID).getValue(),
                packageConfig.get(ARTIFACT_ID).getValue(),
                repoConfig.get(RepoUrl.REPO_URL).getValue()));
        validateConfig(repoConfig, packageConfig);
        LookupParams params = new MavenPackageConfig(packageConfig).getLookupParams(repoConfig, null);
        PackageRevision packageRevision = poll(params);
        LOGGER.info(String.format("getLatestRevision returning with %s, %s",
                packageRevision.getRevision(), packageRevision.getTimestamp()));
        return packageRevision;
    }

    public PackageRevision latestModificationSince(PackageConfigurations packageConfig, PackageConfigurations repoConfig, PackageRevision previouslyKnownRevision) {
        LOGGER.info(String.format("latestModificationSince called with groupId %s, for repo: %s",
                packageConfig.get(GROUP_ID).getValue(), repoConfig.get(RepoUrl.REPO_URL).getValue()));
        validateConfig(repoConfig, packageConfig);
        LookupParams params = new MavenPackageConfig(packageConfig).getLookupParams(repoConfig, previouslyKnownRevision);
        PackageRevision updatedPackage = poll(params);
        if (updatedPackage == null) {
            LOGGER.info(String.format("no modification since %s", previouslyKnownRevision.getRevision()));
            return null;
        }
        LOGGER.info(String.format("latestModificationSince returning with %s, %s",
                updatedPackage.getRevision(), updatedPackage.getTimestamp()));
        if (updatedPackage.getTimestamp().getTime() < previouslyKnownRevision.getTimestamp().getTime())
            LOGGER.warn(String.format("Updated Package %s published earlier (%s) than previous (%s, %s)",
                    updatedPackage.getRevision(), updatedPackage.getTimestamp(), previouslyKnownRevision.getRevision(), previouslyKnownRevision.getTimestamp()));
        return updatedPackage;
    }

    @Override
    public OperationResponse checkConnectionToRepository(PackageConfigurations packageConfigurations) {
        RepoUrl repoUrl = new MavenRepoConfig(packageConfigurations).getRepoUrl();
        OperationResponse response = new OperationResponse();
        try {
            boolean result = new RepositoryConnector().testConnection(repoUrl.forDisplay(), repoUrl.getCredentials().getUser(), repoUrl.getCredentials().getPassword());
            if (result) {
                response.withSuccessMessages("Connection ok");
            } else {
                response.withErrorMessages("Connection failed");
            }
        } catch (Exception e) {
            response.withErrorMessages(e.getMessage());
        }
        return response;
    }

    private void validateConfig(PackageConfigurations repoConfig, PackageConfigurations packageConfig) {
        Errors errors = new Errors();
        new PluginConfig().isRepositoryConfigurationValid(repoConfig, errors);
        new PluginConfig().isPackageConfigurationValid(packageConfig, repoConfig, errors);
        if (errors.hasErrors()) {
            StringBuilder stringBuilder = new StringBuilder();
            for (ValidationError validationError : errors.getErrors()) {
                stringBuilder.append(validationError.getMessage()).append("; ");
            }
            String errorString = stringBuilder.toString();
            throw new RuntimeException(errorString.substring(0, errorString.length() - 2));
        }
    }

    PackageRevision poll(LookupParams params) {
        Version latest = new MavenRepositoryClient(params).getLatest();
        if(latest == null) return null;
        return latest.toPackageRevision();
    }
}

@@ -3447,36 +3447,26 @@
 rations 
-packageConfiguration
+repoConfig
 s) %7B%0A   
@@ -3512,28 +3512,18 @@
 fig(
-packageConfiguration
+repoConfig
 s).g
@@ -3796,16 +3796,17 @@
     if (
+!
 result) 
@@ -3840,15 +3840,13 @@
 with
-Success
+Error
 Mess
@@ -3855,50 +3855,94 @@
 es(%22
-Connection ok%22);%0A            %7D else %7B%0A    
+Did not get HTTP Status 200 response%22);%0A            %7D%0A        %7D catch (Exception e) %7B%0A
     
@@ -3980,42 +3980,43 @@
 ges(
-%22Connection failed%22
+e.getMessage()
 );%0A    
+    %7D%0A
         
 %7D%0A  
@@ -4015,96 +4015,497 @@
     
-%7D
+return response;
 %0A    
+%7D%0A%0A
     
-%7D catch (Exception e) %7B%0A            response.withErrorMessages(e.getMessag
+@Override%0A    public OperationResponse checkConnectionToPackage(PackageConfigurations packageConfigs, PackageConfigurations repoConfigs) %7B%0A        OperationResponse repoCheckResponse = checkConnectionToRepository(repoConfigs);%0A        if(!repoCheckResponse.isSuccessful())%0A            return repoCheckResponse;%0A        PackageRevision packageRevision = getLatestRevision(packageConfigs, repoConfigs);%0A        OperationResponse response = new OperationRespons
 e()
-)
 ;%0A  
@@ -4502,33 +4502,101 @@
 onse();%0A        
-%7D
+response.withSuccessMessages(%22Found %22+packageRevision.getRevision());
 %0A        return 

check connection