/*
 * Certain versions of software and/or documents ("Material") accessible here may contain branding from
 * Hewlett-Packard Company (now HP Inc.) and Hewlett Packard Enterprise Company.  As of September 1, 2017,
 * the Material is now offered by Micro Focus, a separately owned and operated company.  Any reference to the HP
 * and Hewlett Packard Enterprise/HPE marks is historical in nature, and the HP and Hewlett Packard Enterprise/HPE
 * marks are the property of their respective owners.
 * __________________________________________________________________
 * MIT License
 *
 * (c) Copyright 2012-2019 Micro Focus or one of its affiliates.
 *
 * The only warranties for products and services of Micro Focus and its affiliates
 * and licensors ("Micro Focus") are set forth in the express warranty statements
 * accompanying such products and services. Nothing herein should be construed as
 * constituting an additional warranty. Micro Focus shall not be liable for technical
 * or editorial errors or omissions contained herein.
 * The information contained herein is subject to change without notice.
 * ___________________________________________________________________
 */

package com.microfocus.application.automation.tools.octane.model;

import com.microfocus.application.automation.tools.sse.common.StringUtils;
import hudson.EnvVars;
import hudson.maven.MavenModuleSet;
import hudson.maven.MavenModuleSetBuild;
import hudson.model.*;
import hudson.plugins.sonar.SonarGlobalConfiguration;
import hudson.plugins.sonar.SonarInstallation;
import hudson.plugins.sonar.SonarRunnerBuilder;
import hudson.tasks.Builder;
import hudson.util.DescribableList;
import hudson.util.Secret;
import jenkins.model.GlobalConfiguration;

import java.io.IOException;
import java.util.Arrays;
import java.util.Optional;

/**
 * the adapter enables usage of sonar classes and interfaces without adding a full dependency on
 * sonar plugin.
 * this class is only dependent on sonar plugin for compile time.
 */

public class SonarHelper {

    public enum DataType {VULNERABILITIES, COVERAGE}

    public static final String SONAR_GLOBAL_CONFIG = "hudson.plugins.sonar.SonarGlobalConfiguration";
    private static final String SONAR_ACTION_ID = "hudson.plugins.sonar.SonarRunnerBuilder";
    private static final String SONAR_SERVER_HOST_VARIABLE = "SONAR_HOST_URL";
    private static final String SONAR_SERVER_TOKEN_VARIABLE = "SONAR_AUTH_TOKEN";

    private String serverUrl;
    private String serverToken;

    public SonarHelper(Run<?, ?> run, TaskListener listener) {
        DescribableList<Builder, Descriptor<Builder>> postbuilders = null;
        if (run instanceof AbstractBuild) {
            AbstractBuild abstractBuild = (AbstractBuild) run;
            setSonarDetailsFromMavenEnvironment(abstractBuild, listener);
            AbstractProject project = abstractBuild.getProject();

            // for jobs that does not use new sonar approach for maven jobs,
            // extract data for old approach which used post build step
            if (StringUtils.isNullOrEmpty(this.getServerUrl()) || StringUtils.isNullOrEmpty(this.getServerToken())) {
                if (project instanceof MavenModuleSet) {
                    postbuilders = ((MavenModuleSet) project).getPostbuilders();
                } else if (project instanceof Project) {
                    postbuilders = ((Project) project).getBuildersList();
                }
                if (postbuilders != null){
                    setDataFromSonarBuilder(postbuilders);
                }
            }
        }
    }

    public String getServerUrl() {
        return serverUrl;
    }

    public String getServerToken() {
        return serverToken;
    }

    // used by the web hook
    public static String getSonarInstallationTokenByUrl(GlobalConfiguration sonarConfiguration, String sonarUrl) {
        if (sonarConfiguration instanceof SonarGlobalConfiguration) {
            SonarGlobalConfiguration sonar = (SonarGlobalConfiguration) sonarConfiguration;
            Optional<SonarInstallation> installation = Arrays.stream(sonar.getInstallations())
                    .filter(sonarInstallation -> sonarInstallation.getServerUrl().equals(sonarUrl))
                    .findFirst();
            if (installation.isPresent()) {
                return Secret.toString(installation.get().getServerAuthenticationToken());
            }
        }
        return "";
    }

    private void setSonarDetailsFromMavenEnvironment(AbstractBuild build, TaskListener listener) {
        EnvVars environment;
        try {
            environment = build.getEnvironment(listener);
            if (environment != null) {
                this.serverUrl = environment.get(SONAR_SERVER_HOST_VARIABLE, "");
                this.serverToken = environment.get(SONAR_SERVER_TOKEN_VARIABLE, "");
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void setDataFromSonarBuilder(DescribableList<Builder, Descriptor<Builder>> postBuilders) {
        Builder sonarBuilder = postBuilders.getDynamic(SONAR_ACTION_ID);
        if (sonarBuilder != null) {
            SonarRunnerBuilder builder = (SonarRunnerBuilder) sonarBuilder;
            this.serverUrl = extractSonarUrl(builder);
            this.serverToken = extractSonarToken(builder);
        }
    }

    /**
     * get sonar URL address
     *
     * @return Sonar's URL
     */
    private String extractSonarUrl(SonarRunnerBuilder builder) {
        return builder != null ? builder.getSonarInstallation().getServerUrl() : "";
    }

    /**
     * get sonar server token
     *
     * @return Sonar's auth token
     */
    private String extractSonarToken(SonarRunnerBuilder builder) {
        return builder != null ? Secret.toString(builder.getSonarInstallation().getServerAuthenticationToken()) : "";
    }
}

@@ -4331,31 +4331,37 @@
     
-return Secret.toString(
+Object authenticationToken = 
 inst
@@ -4405,18 +4405,428 @@
 nToken()
-)
 ;
+%0A                if (authenticationToken != null)%7B%0A                   if (authenticationToken instanceof Secret)%7B  //new versions of sonarqube scanner%0A                       return Secret.toString((Secret) authenticationToken);%0A                   %7D%0A                   else%7B // old versions of sonarqube scanner%0A                       return authenticationToken.toString();%0A                   %7D%0A                %7D
 %0A       
@@ -6204,38 +6204,60 @@
 lder) %7B%0A        
-return
+Object authenticationToken =
  builder != null
@@ -6261,26 +6261,11 @@
 ull 
+ 
 ? 
-Secret.toString(
 buil
@@ -6321,19 +6321,391 @@
 nToken()
-)
  :
+ %22%22;%0A%0A        if (authenticationToken != null)%7B%0A            if (authenticationToken instanceof Secret)%7B  //new versions of sonarqube scanner%0A                return Secret.toString((Secret) authenticationToken);%0A            %7D%0A            else%7B // old versions of sonarqube scanner%0A                return authenticationToken.toString();%0A            %7D%0A        %7D%0A        return
  %22%22;%0A   

add support for older versions of sonarqube scanner that don't use Secert object to store authentication token