/*
 * The MIT License
 *
 * Copyright (c) 2015, Mads Mohr Christensen
 *
 * 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.jenkinsci.plugins.newrelicnotifier;

import com.cloudbees.plugins.credentials.common.UsernamePasswordCredentials;
import hudson.EnvVars;
import hudson.Extension;
import hudson.Launcher;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.model.Result;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.BuildStepMonitor;
import hudson.tasks.Notifier;
import hudson.tasks.Publisher;
import hudson.util.Secret;
import org.jenkinsci.plugins.newrelicnotifier.api.NewRelicClient;
import org.jenkinsci.plugins.newrelicnotifier.api.NewRelicClientImpl;
import org.kohsuke.stapler.DataBoundConstructor;

import java.io.IOException;
import java.util.List;

/**
 * Notifies a New Relic instance about deployment.
 */
public class NewRelicDeploymentNotifier extends Notifier {

    private final NewRelicClient client = new NewRelicClientImpl();

    private final List<DeploymentNotificationBean> notifications;

    @DataBoundConstructor
    public NewRelicDeploymentNotifier(List<DeploymentNotificationBean> notifications) {
        super();
        this.notifications = notifications;
    }

    public List<DeploymentNotificationBean> getNotifications() {
        return notifications;
    }

    @Override
    public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
        boolean result = false;
        if (build.getResult() == Result.SUCCESS) {
            EnvVars envVars = build.getEnvironment(listener);
            envVars.overrideAll(build.getBuildVariables());

            for (DeploymentNotificationBean n : getNotifications()) {
                UsernamePasswordCredentials credentials = DeploymentNotificationBean.getCredentials(build.getProject(), n.getApiKey(), client.getApiEndpoint());
                if (credentials == null) {
                    listener.getLogger().println("Invalid credentials for Application ID: " + n.getApplicationId());
                } else {
                    if (client.sendNotification(
                            Secret.toString(credentials.getPassword()),
                            n.getApplicationId(),
                            n.getDescription(envVars),
                            n.getRevision(envVars),
                            n.getChangelog(envVars),
                            n.getUser(envVars))) {
                        listener.getLogger().println("Notified New Relic. Application ID: " + n.getApplicationId());
                        result = true;
                    } else {
                        listener.getLogger().println("Failed to notify New Relic. Application ID: " + n.getApplicationId());
                    }
                }
            }
        } else {
            listener.getLogger().println("Build unsuccessful. Skipping New Relic Deployment notification.");
        }
        return result;
    }

    @Override
    public BuildStepMonitor getRequiredMonitorService() {
        return BuildStepMonitor.NONE;
    }

    @Override
    public DescriptorImpl getDescriptor() {
        return (DescriptorImpl) super.getDescriptor();
    }

    @Extension
    public static final class DescriptorImpl extends BuildStepDescriptor<Publisher> {

        @Override
        public boolean isApplicable(Class<? extends AbstractProject> jobType) {
            return true;
        }

        @Override
        public String getDisplayName() {
            return "New Relic Deployment Notifications";
        }
    }
}

@@ -2602,15 +2602,15 @@
 t = 
-fals
+tru
 e;%0A
+%0A
     
@@ -2649,23 +2649,215 @@
 ult.
-SUCCESS) %7B%0A    
+FAILED %7C%7C%0A            build.getResult() == Result.ABORTED) %7B%0A            listener.getLogger().println(%22Build unsuccessful. Skipping New Relic Deployment notification.%22);%0A            return false;%0A        %7D%0A%0A
     
@@ -2918,20 +2918,16 @@
         
-    
 envVars.
@@ -2967,20 +2967,16 @@
 es());%0A%0A
-    
         
@@ -3029,28 +3029,24 @@
 ations()) %7B%0A
-    
             
@@ -3198,28 +3198,24 @@
             
-    
 if (credenti
@@ -3237,36 +3237,32 @@
                 
-    
 listener.getLogg
@@ -3354,37 +3354,61 @@
             
-%7D else %7B
+result = false;
 %0A    
+        %7D else %7B%0A
             
@@ -3443,37 +3443,8 @@
 ion(
-%0A                            
 Secr
@@ -3507,24 +3507,40 @@
             
+                
 n.getApplica
@@ -3573,24 +3573,40 @@
             
+                
 n.getDescrip
@@ -3644,24 +3644,40 @@
             
+                
 n.getRevisio
@@ -3712,24 +3712,40 @@
             
+                
 n.getChangel
@@ -3781,24 +3781,40 @@
             
+                
 n.getUser(en
@@ -3820,28 +3820,24 @@
 nvVars))) %7B%0A
-    
             
@@ -3941,51 +3941,8 @@
 ));%0A
-                        result = true;%0A    
     
@@ -3974,36 +3974,32 @@
                 
-    
 listener.getLogg
@@ -4107,27 +4107,23 @@
     
-%7D%0A                %7D
+result = false;
 %0A   
@@ -4132,29 +4132,16 @@
     
-   %7D%0A
        
- %7D else %7B
+%7D
 %0A   
@@ -4153,104 +4153,9 @@
     
-listener.getLogger().println(%22Build unsuccessful. Skipping New Relic Deployment notification.%22);
+%7D
 %0A   

deal with UNSTABLE builds as well