package com.openshift.jenkins.plugins.pipeline.model;

import com.openshift.jenkins.plugins.pipeline.MessageConstants;
import com.openshift.restclient.IClient;
import com.openshift.restclient.ResourceKind;
import com.openshift.restclient.model.IDeploymentConfig;
import com.openshift.restclient.model.IReplicationController;
import hudson.Launcher;
import hudson.model.TaskListener;

import java.util.Map;

public interface IOpenShiftDeployer extends ITimedOpenShiftPlugin {

    final static String DISPLAY_NAME = "Trigger OpenShift Deployment";

    default String getDisplayName() {
        return DISPLAY_NAME;
    }

    String getDepCfg();

    default long getGlobalTimeoutConfiguration() {
        return GlobalConfig.getDeployWait();
    }

    default String getDepCfg(Map<String, String> overrides) {
        return getOverride(getDepCfg(), overrides);
    }

    default boolean bumpVersion(IDeploymentConfig dc, IClient client, TaskListener listener, Map<String, String> overrides) {
        int latestVersion = dc.getLatestVersionNumber() + 1;
        boolean chatty = Boolean.parseBoolean(getVerbose(overrides));
        try {
            dc.setLatestVersionNumber(latestVersion);
            client.update(dc);
            if (chatty)
                listener.getLogger().println("\nOpenShiftDeployer latest version now " + dc.getLatestVersionNumber());

        } catch (Throwable t) {
            if (chatty)
                t.printStackTrace(listener.getLogger());
            return false;
        }
        return true;
    }

    default boolean coreLogic(Launcher launcher, TaskListener listener, Map<String, String> overrides) {
        boolean chatty = Boolean.parseBoolean(getVerbose(overrides));
        listener.getLogger().println(String.format(MessageConstants.START_DEPLOY_RELATED_PLUGINS, DISPLAY_NAME, getDepCfg(overrides), getNamespace(overrides)));

        // get oc client
        IClient client = this.getClient(listener, DISPLAY_NAME, overrides);

        if (client != null) {
            // do the oc deploy with version bump ... may need to retry
            long currTime = System.currentTimeMillis();
            boolean deployDone = false;
            boolean versionBumped = false;
            String state = null;
            IDeploymentConfig dc = null;
            IReplicationController rc = null;
            long wait = getTimeout(listener, chatty, overrides);
            while (System.currentTimeMillis() < (currTime + wait)) {
                dc = client.get(ResourceKind.DEPLOYMENT_CONFIG, getDepCfg(overrides), getNamespace(overrides));
                if (dc != null) {
                    if (!versionBumped) {
                        // allow some retry in case the dc creation request happened before this step ran
                        versionBumped = bumpVersion(dc, client, listener, overrides);
                    }

                    try {
                        rc = getLatestReplicationController(dc, getNamespace(overrides), client, chatty ? listener : null);
                        if (chatty)
                            listener.getLogger().println("\nOpenShiftDeployer returned rep ctrl " + rc);
                        if (rc != null) {
                            annotateJobInfoToResource(client, listener, chatty, overrides, rc);
                            state = this.getReplicationControllerState(rc);
                            if (this.isDeployFinished(state)) {
                                if (state.equalsIgnoreCase(STATE_FAILED)) {
                                    listener.getLogger().println(String.format(MessageConstants.EXIT_DEPLOY_RELATED_PLUGINS_BAD, DISPLAY_NAME, rc.getName(), state));
                                    return false;
                                }
                                if (state.equalsIgnoreCase(STATE_COMPLETE)) {
                                    deployDone = true;
                                }
                            } else {
                                if (chatty)
                                    listener.getLogger().println("\nOpenShiftDeploy current phase " + state);
                            }
                        } else {
                            if (chatty)
                                listener.getLogger().println("\nOpenShiftDeploy no rc for latest version yet");
                        }
                    } catch (Throwable t) {
                        if (chatty)
                            t.printStackTrace(listener.getLogger());
                    }


                    if (deployDone) {
                        break;
                    } else {
                        if (chatty)
                            listener.getLogger().println("\nOpenShiftDeployer wait 10 seconds, then try oc deploy again");
                        try {
                            Thread.sleep(10000);
                        } catch (InterruptedException e) {
                        }
                    }


                }
            }

            if (!deployDone) {
                if (dc != null)
                    listener.getLogger().println(String.format(MessageConstants.EXIT_DEPLOY_TRIGGER_TIMED_OUT, DISPLAY_NAME, (rc != null ? rc.getName() : "<deployment not found>"), state));
                else
                    listener.getLogger().println(String.format(MessageConstants.EXIT_DEPLOY_RELATED_PLUGINS_NO_CFG, DISPLAY_NAME, getDepCfg(overrides)));
                return false;
            }

            listener.getLogger().println(String.format(MessageConstants.EXIT_DEPLOY_RELATED_PLUGINS_GOOD_REPLICAS_IGNORED, DISPLAY_NAME, rc.getName()));
            return true;


        } else {
            return false;
        }
    }

}

@@ -199,16 +199,155 @@
 ceKind;%0A
+import com.openshift.restclient.capability.CapabilityVisitor;%0Aimport com.openshift.restclient.capability.resources.IDeploymentTriggerable;%0A
 import c
@@ -453,24 +453,25 @@
 Controller;%0A
+%0A
 import hudso
@@ -1008,685 +1008,8 @@
  %7D%0A%0A
-    default boolean bumpVersion(IDeploymentConfig dc, IClient client, TaskListener listener, Map%3CString, String%3E overrides) %7B%0A        int latestVersion = dc.getLatestVersionNumber() + 1;%0A        boolean chatty = Boolean.parseBoolean(getVerbose(overrides));%0A        try %7B%0A            dc.setLatestVersionNumber(latestVersion);%0A            client.update(dc);%0A            if (chatty)%0A                listener.getLogger().println(%22%5CnOpenShiftDeployer latest version now %22 + dc.getLatestVersionNumber());%0A%0A        %7D catch (Throwable t) %7B%0A            if (chatty)%0A                t.printStackTrace(listener.getLogger());%0A            return false;%0A        %7D%0A        return true;%0A    %7D%0A%0A
     
@@ -1477,80 +1477,8 @@
 ) %7B%0A
-            // do the oc deploy with version bump ... may need to retry%0A
     
@@ -1678,32 +1678,76 @@
 nfig dc = null;%0A
+            IDeploymentConfig newdc = null;%0A
             IRep
@@ -2232,69 +2232,1180 @@
     
-versionBumped = bumpVersion(dc, client, listener, overrides);
+try %7B%0A                            final String dcName = dc.getName();%0A                            newdc = dc.accept(new CapabilityVisitor%3CIDeploymentTriggerable, IDeploymentConfig%3E() %7B%0A%0A                                @Override%0A                                public IDeploymentConfig visit(IDeploymentTriggerable triggerable) %7B%0A                                    triggerable.setForce(true);%0A                                    triggerable.setLatest(true);%0A                                    triggerable.setResourceName(dcName);%0A                                    return triggerable.trigger();%0A                                %7D%0A                                %0A                            %7D, null);%0A                            if (chatty)%0A                                listener.getLogger().println(%22%5CnOpenShiftDeployer latest version now %22 + newdc.getLatestVersionNumber());%0A                            versionBumped = newdc.getLatestVersionNumber() %3E dc.getLatestVersionNumber();%0A                        %7D catch (Throwable t) %7B%0A                            if (chatty)%0A                                t.printStackTrace(listener.getLogger());%0A                        %7D
 %0A   
@@ -3510,16 +3510,19 @@
 troller(
+new
 dc, getN
@@ -5615,32 +5615,35 @@
             if (
+new
 dc != null)%0A    

change to trigger deployment via instantiate endpoint if available