/*
 * Copyright (c) 2014 T-Systems Multimedia Solutions GmbH
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package de.tsystems.mms.apm.performancesignature.dynatrace;

import de.tsystems.mms.apm.performancesignature.dynatrace.rest.DTServerConnection;
import de.tsystems.mms.apm.performancesignature.dynatrace.rest.json.ApiException;
import de.tsystems.mms.apm.performancesignature.dynatrace.rest.json.api.AlertsIncidentsAndEventsApi;
import de.tsystems.mms.apm.performancesignature.dynatrace.rest.json.model.DeploymentEvent;
import de.tsystems.mms.apm.performancesignature.dynatrace.rest.json.model.EventUpdate;
import de.tsystems.mms.apm.performancesignature.dynatrace.rest.xml.RESTErrorException;
import de.tsystems.mms.apm.performancesignature.util.PerfSigUtils;
import hudson.AbortException;
import hudson.model.TaskListener;
import org.jenkinsci.plugins.workflow.steps.BodyExecution;
import org.jenkinsci.plugins.workflow.steps.BodyExecutionCallback;
import org.jenkinsci.plugins.workflow.steps.StepContext;
import org.jenkinsci.plugins.workflow.steps.StepExecution;

import javax.annotation.Nonnull;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Date;

public class CreateDeploymentStepExecution extends StepExecution {
    private final transient CreateDeploymentStep step;
    private final transient TaskListener listener;
    private BodyExecution body;
    private String eventId;

    private transient PrintStream console;

    CreateDeploymentStepExecution(CreateDeploymentStep createDeploymentStep, StepContext context) throws IOException, InterruptedException {
        super(context);
        this.step = createDeploymentStep;
        this.listener = context.get(TaskListener.class);
    }

    @Override
    public boolean start() throws Exception {
        console = listener.getLogger();
        StepContext context = getContext();

        DTServerConnection connection = PerfSigUtils.createDTServerConnection(step.getDynatraceProfile());
        AlertsIncidentsAndEventsApi api = new AlertsIncidentsAndEventsApi(connection.getApiClient());

        DeploymentEvent event = new DeploymentEvent(null, null, "ongoing Deployment",
                "deployment event created by Jenkins", new Date(), null, connection.getCredProfilePair().getProfile(), null);
        eventId = api.createDeploymentEvent(event);
        if (eventId == null) {
            throw new AbortException("could not create deployment event");
        }
        console.println("successfully created deployment event " + eventId);

        body = context.newBodyInvoker()
                .withCallback(new Callback())
                .start();
        return false;
    }

    @Override
    public void stop(@Nonnull Throwable cause) throws Exception {
        if (body != null) {
            body.cancel(cause);
        }
        updateEvent();
    }

    private void updateEvent() throws ApiException, AbortException, RESTErrorException {
        if (eventId != null) {
            DTServerConnection connection = PerfSigUtils.createDTServerConnection(step.getDynatraceProfile());
            AlertsIncidentsAndEventsApi api = new AlertsIncidentsAndEventsApi(connection.getApiClient());
            EventUpdate event = new EventUpdate(new Date());
            api.updateDeploymentEvent(eventId, event);
            console.println("successfully updated deployment event " + eventId);
        }
    }

    private class Callback extends BodyExecutionCallback.TailCall {

        private static final long serialVersionUID = 1L;

        @Override
        protected void finished(StepContext context) throws Exception {
            updateEvent();
        }

    }

}

@@ -1660,22 +1660,49 @@
 ava.
-io.PrintStream
+util.Date;%0Aimport java.util.logging.Level
 ;%0Aim
@@ -1716,20 +1716,30 @@
 va.util.
-Date
+logging.Logger
 ;%0A%0Apubli
@@ -1796,24 +1796,183 @@
 Execution %7B%0A
+    private static final long serialVersionUID = 1L;%0A    private static final Logger LOGGER = Logger.getLogger(CreateDeploymentStepExecution.class.getName());%0A
     private 
@@ -2018,59 +2018,8 @@
 ep;%0A
-    private final transient TaskListener listener;%0A
     
@@ -2079,52 +2079,8 @@
 d;%0A%0A
-    private transient PrintStream console;%0A%0A
     
@@ -2286,65 +2286,8 @@
 ep;%0A
-        this.listener = context.get(TaskListener.class);%0A
     
@@ -2353,48 +2353,8 @@
 n %7B%0A
-        console = listener.getLogger();%0A
     
@@ -2984,39 +2984,54 @@
       %7D%0A        
-console
+listener().getLogger()
 .println(%22succes
@@ -3867,15 +3867,30 @@
     
-console
+listener().getLogger()
 .pri
@@ -3956,32 +3956,276 @@
        %7D%0A    %7D%0A%0A
+    private TaskListener listener() %7B%0A        try %7B%0A            return getContext().get(TaskListener.class);%0A        %7D catch (Exception x) %7B%0A            LOGGER.log(Level.WARNING, null, x);%0A            return TaskListener.NULL;%0A        %7D%0A    %7D%0A%0A
     private clas
@@ -4276,17 +4276,16 @@
 lCall %7B%0A
-%0A
         
@@ -4468,11 +4468,10 @@
 %0A%0A    %7D%0A
-%0A
 %7D%0A

fix fb warnings