package com.sumologic.jenkins.jenkinssumologicplugin;

import com.google.gson.Gson;
import com.sumologic.jenkins.jenkinssumologicplugin.model.ModelFactory;
import com.sumologic.jenkins.jenkinssumologicplugin.sender.LogSender;
import hudson.Launcher;
import hudson.model.*;
import hudson.tasks.BuildStepMonitor;
import hudson.tasks.Notifier;
import hudson.tasks.Publisher;
import org.kohsuke.stapler.DataBoundConstructor;

import java.io.IOException;
import java.util.Map;
import java.util.logging.Logger;

/**
 * This publisher will sendLogs build metadata to a Sumologic HTTP collector.
 *
 * Created by deven on 7/6/15.
 */
public class SumoBuildNotifier extends Notifier {

  private final static Logger LOG = Logger.getLogger(SumoBuildNotifier.class.getName());
  private LogSender logSender;

  @DataBoundConstructor
  public SumoBuildNotifier() {
    super();
    logSender = LogSender.getInstance();
  }

  @SuppressWarnings("unchecked")
  public static SumoBuildNotifier getNotifier(AbstractProject project) {
    Map<Descriptor<Publisher>, Publisher> map = project.getPublishersList().toMap();
    for (Publisher publisher : map.values()) {
      if (publisher instanceof SumoBuildNotifier) {
        return (SumoBuildNotifier) publisher;
      }
    }
    return null;
  }

  @Override
  public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
    send(build, listener);
    return true;
  }

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

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

  protected void send(AbstractBuild build, TaskListener listener) {
    Gson gson = new Gson();
    String json = gson.toJson(ModelFactory.createBuildModel(build));

    PluginDescriptorImpl descriptor = getDescriptor();

    LOG.info("Uploading build status to sumologic: " + json);
    logSender.sendLogs(descriptor.getUrl(), json.getBytes(), descriptor.getSourceName(), descriptor.getSourceCategory());
  }
}

@@ -361,24 +361,68 @@
 .Publisher;%0A
+import org.apache.commons.lang.StringUtils;%0A
 import org.k
@@ -813,16 +813,23 @@
 private 
+static 
 LogSende
@@ -839,16 +839,42 @@
 ogSender
+ = LogSender.getInstance()
 ;%0A%0A  @Da
@@ -940,49 +940,8 @@
 ();%0A
-    logSender = LogSender.getInstance();%0A
   %7D%0A
@@ -1945,19 +1945,22 @@
 iptor = 
-get
+Plugin
 Descript
@@ -1957,24 +1957,40 @@
 inDescriptor
+Impl.getInstance
 ();%0A%0A    LOG
@@ -2048,68 +2048,70 @@
 n);%0A
+%0A
     
-logSender.sendLogs(descriptor.getUrl(), json.getBytes(),
+String url = descriptor.getUrl();%0A    String sourceName =
  des
@@ -2133,17 +2133,39 @@
 ceName()
-,
+;%0A    String category =
  descrip
@@ -2187,16 +2187,110 @@
 tegory()
+;%0A    byte%5B%5D bytes = json.getBytes();%0A%0A    logSender.sendLogs(url, bytes, sourceName, category
 );%0A  %7D%0A%7D

fix logger initialization