// Path: src/main/java/org/datadog/jenkins/plugins/datadog/util/TagsUtil.java
// public class TagsUtil {
// 
//     public static Map<String, Set<String>> merge(Map<String, Set<String>> dest, Map<String, Set<String>> orig) {
//         if (dest == null) {
//             dest = new HashMap<>();
//         }
//         if (orig == null) {
//             orig = new HashMap<>();
//         }
//         for (String oName: orig.keySet()){
//             Set<String> dValues = dest.containsKey(oName) ? dest.get(oName) : new HashSet<String>();
//             if (dValues == null) {
//                 dValues = new HashSet<>();
//             }
//             Set<String> oValues = orig.get(oName);
//             if (oValues != null) {
//                 dValues.addAll(oValues);
//             }
//             dest.put(oName, dValues);
//         }
//         return dest;
//     }
// 
//     public static JSONArray convertTagsToJSONArray(Map<String, Set<String>> tags){
//         JSONArray result = new JSONArray();
//         for (String name : tags.keySet()) {
//             Set<String> values = tags.get(name);
//             for (String value : values){
//                 if ("".equals(value)){
//                     result.add(name); // Tag with no value
//                 }else{
//                     result.add(String.format("%s:%s", name, value));
//                 }
//             }
//         }
//         return result;
//     }
// 
//     public static String[] convertTagsToArray(Map<String, Set<String>> tags){
//         List<String> result = new ArrayList<>();
//         for (String name : tags.keySet()) {
//             Set<String> values = tags.get(name);
//             for (String value : values){
//                 if("".equals(value)){
//                     result.add(name);
//                 }else{
//                     result.add(String.format("%s:%s", name, value));
//                 }
//             }
//         }
//         Collections.sort(result);
//         return result.toArray(new String[0]);
//     }
// }


import jenkins.model.Jenkins;
import org.datadog.jenkins.plugins.datadog.util.TagsUtil;
import javax.annotation.Nonnull;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Inet4Address;
import java.net.UnknownHostException;
import java.util.*;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import hudson.EnvVars;
import hudson.ExtensionList;
import hudson.XmlFile;
import hudson.model.*;
import hudson.model.labels.LabelAtom;
/*
The MIT License

Copyright (c) 2015-Present Datadog, Inc <opensource@datadoghq.com>
All rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
 */

package org.datadog.jenkins.plugins.datadog;



public class DatadogUtilities {

    private static final Logger logger = Logger.getLogger(DatadogUtilities.class.getName());

    private static final Integer MAX_HOSTNAME_LEN = 255;

    /**
     * @return - The descriptor for the Datadog plugin. In this case the global configuration.
     */
    public static DatadogGlobalConfiguration getDatadogGlobalDescriptor() {
        Jenkins jenkins = Jenkins.getInstance();
        if (jenkins == null) {
            return null;
        }
        return ExtensionList.lookup(DatadogGlobalConfiguration.class).get(DatadogGlobalConfiguration.class);
    }

    /**
     * @param r - Current build.
     * @return - The configured {@link DatadogJobProperty}. Null if not there
     */
    public static DatadogJobProperty getDatadogJobProperties(@Nonnull Run r) {
        return (DatadogJobProperty) r.getParent().getProperty(DatadogJobProperty.class);
    }

    /**
     * Builds extraTags if any are configured in the Job.
     *
     * @param run      - Current build
     * @param listener - Current listener
     * @return A {@link HashMap} containing the key,value pairs of tags if any.
     */
    public static Map<String, Set<String>> getBuildTags(Run run, @Nonnull TaskListener listener) {
        Map<String, Set<String>> result = new HashMap<>();
        String jobName = run.getParent().getFullName();
        final String globalJobTags = getDatadogGlobalDescriptor().getGlobalJobTags();
        final DatadogJobProperty property = DatadogUtilities.getDatadogJobProperties(run);
        String workspaceTagFile = property.readTagFile(run);
        // If job doesn't have a workspace Tag File set we check if one has been defined globally
        if(workspaceTagFile == null){
            workspaceTagFile = getDatadogGlobalDescriptor().getGlobalTagFile();
        }
        try {
            final EnvVars envVars = run.getEnvironment(listener);
            if (workspaceTagFile != null) {
// Path: src/main/java/org/datadog/jenkins/plugins/datadog/util/TagsUtil.java
// public class TagsUtil {
// 
//     public static Map<String, Set<String>> merge(Map<String, Set<String>> dest, Map<String, Set<String>> orig) {
//         if (dest == null) {
//             dest = new HashMap<>();
//         }
//         if (orig == null) {
//             orig = new HashMap<>();
//         }
//         for (String oName: orig.keySet()){
//             Set<String> dValues = dest.containsKey(oName) ? dest.get(oName) : new HashSet<String>();
//             if (dValues == null) {
//                 dValues = new HashSet<>();
//             }
//             Set<String> oValues = orig.get(oName);
//             if (oValues != null) {
//                 dValues.addAll(oValues);
//             }
//             dest.put(oName, dValues);
//         }
//         return dest;
//     }
// 
//     public static JSONArray convertTagsToJSONArray(Map<String, Set<String>> tags){
//         JSONArray result = new JSONArray();
//         for (String name : tags.keySet()) {
//             Set<String> values = tags.get(name);
//             for (String value : values){
//                 if ("".equals(value)){
//                     result.add(name); // Tag with no value
//                 }else{
//                     result.add(String.format("%s:%s", name, value));
//                 }
//             }
//         }
//         return result;
//     }
// 
//     public static String[] convertTagsToArray(Map<String, Set<String>> tags){
//         List<String> result = new ArrayList<>();
//         for (String name : tags.keySet()) {
//             Set<String> values = tags.get(name);
//             for (String value : values){
//                 if("".equals(value)){
//                     result.add(name);
//                 }else{
//                     result.add(String.format("%s:%s", name, value));
//                 }
//             }
//         }
//         Collections.sort(result);
//         return result.toArray(new String[0]);
//     }
// }


// Path: src/main/java/org/datadog/jenkins/plugins/datadog/DatadogUtilities.java
import jenkins.model.Jenkins;
import org.datadog.jenkins.plugins.datadog.util.TagsUtil;
import javax.annotation.Nonnull;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Inet4Address;
import java.net.UnknownHostException;
import java.util.*;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import hudson.EnvVars;
import hudson.ExtensionList;
import hudson.XmlFile;
import hudson.model.*;
import hudson.model.labels.LabelAtom;

/*
The MIT License

Copyright (c) 2015-Present Datadog, Inc <opensource@datadoghq.com>
All rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
 */

package org.datadog.jenkins.plugins.datadog;



public class DatadogUtilities {

    private static final Logger logger = Logger.getLogger(DatadogUtilities.class.getName());

    private static final Integer MAX_HOSTNAME_LEN = 255;

    /**
     * @return - The descriptor for the Datadog plugin. In this case the global configuration.
     */
    public static DatadogGlobalConfiguration getDatadogGlobalDescriptor() {
        Jenkins jenkins = Jenkins.getInstance();
        if (jenkins == null) {
            return null;
        }
        return ExtensionList.lookup(DatadogGlobalConfiguration.class).get(DatadogGlobalConfiguration.class);
    }

    /**
     * @param r - Current build.
     * @return - The configured {@link DatadogJobProperty}. Null if not there
     */
    public static DatadogJobProperty getDatadogJobProperties(@Nonnull Run r) {
        return (DatadogJobProperty) r.getParent().getProperty(DatadogJobProperty.class);
    }

    /**
     * Builds extraTags if any are configured in the Job.
     *
     * @param run      - Current build
     * @param listener - Current listener
     * @return A {@link HashMap} containing the key,value pairs of tags if any.
     */
    public static Map<String, Set<String>> getBuildTags(Run run, @Nonnull TaskListener listener) {
        Map<String, Set<String>> result = new HashMap<>();
        String jobName = run.getParent().getFullName();
        final String globalJobTags = getDatadogGlobalDescriptor().getGlobalJobTags();
        final DatadogJobProperty property = DatadogUtilities.getDatadogJobProperties(run);
        String workspaceTagFile = property.readTagFile(run);
        // If job doesn't have a workspace Tag File set we check if one has been defined globally
        if(workspaceTagFile == null){
            workspaceTagFile = getDatadogGlobalDescriptor().getGlobalTagFile();
        }
        try {
            final EnvVars envVars = run.getEnvironment(listener);
            if (workspaceTagFile != null) {
                result = TagsUtil.merge(result, computeTagListFromVarList(envVars, workspaceTagFile));