/**
 * Copyright (C) 2016 Red Hat, Inc.
 *
 * 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 io.syndesis.rest.v1.handler.tests;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import io.syndesis.dao.init.ModelData;
import io.syndesis.dao.manager.DataAccessObject;
import io.syndesis.dao.manager.DataManager;
import io.syndesis.model.ListResult;
import io.syndesis.model.WithId;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;

@Path("/test-support")
@org.springframework.stereotype.Component
@ConditionalOnProperty(value = "endpoints.test_support.enabled")
public class TestSupportHandler {

    private static final Logger LOG = LoggerFactory.getLogger(TestSupportHandler.class);

    private final DataManager dataMgr;
    private final List<DataAccessObject<?>> daos;

    @Context
    private HttpServletRequest context;

    public TestSupportHandler(DataManager dataMgr, List<DataAccessObject<?>> daos) {
        this.dataMgr = dataMgr;
        this.daos = daos.stream().filter(x -> !x.isReadOnly()).collect(Collectors.toList());
    }

    @GET
    @Path("/reset-db")
    public void resetDBToDefault() {
        LOG.warn("user {} is resetting DB", context.getRemoteUser());
        deleteAllDBEntities();
        dataMgr.resetDeploymentData();
    }

    @POST
    @Path("/restore-db")
    @Consumes(MediaType.APPLICATION_JSON)
    public void restoreDB(ModelData<?>[] data) {
        LOG.warn("user {} is restoring db state", context.getRemoteUser());
        deleteAllDBEntities();
        for (ModelData<?> modelData : data) {
            dataMgr.store(modelData);
        }
    }

    private void deleteAllDBEntities() {
        for (DataAccessObject<?> dao : daos) {
            dataMgr.deleteAll(dao.getType());
        }
    }

    @GET
    @Path("/snapshot-db")
    @Produces(MediaType.APPLICATION_JSON)
    public ArrayList<ModelData<?>> snapshotDB() {
        LOG.info("user {} is making snapshot", context.getRemoteUser());
        ArrayList<ModelData<?>> result = new ArrayList<>();
        for (DataAccessObject<?> dao : daos) {
            ListResult<? extends WithId<?>> l = dao.fetchAll();
            for (WithId<?> entity : l.getItems()) {
                @SuppressWarnings({"unchecked", "rawtypes"})
                ModelData<?> modelData = new ModelData(entity.getKind(), entity);
                result.add(modelData);
            }
        }
        return result;
    }

}

@@ -978,16 +978,48 @@
 aType;%0A%0A
+import io.syndesis.core.Tokens;%0A
 import i
@@ -1049,16 +1049,16 @@
 elData;%0A
-
 import i
@@ -1213,16 +1213,163 @@
 ithId;%0A%0A
+import io.syndesis.model.integration.Integration;%0Aimport io.syndesis.openshift.OpenShiftDeployment;%0Aimport io.syndesis.openshift.OpenShiftService;%0A
 import o
@@ -1840,16 +1840,69 @@
 %3E%3E daos;
+%0A    private final OpenShiftService openShiftService;
 %0A%0A    @C
@@ -2026,24 +2026,59 @@
 ect%3C?%3E%3E daos
+, OpenShiftService openShiftService
 ) %7B%0A        
@@ -2190,24 +2190,74 @@
 .toList());%0A
+        this.openShiftService = openShiftService;%0A
     %7D%0A%0A    @
@@ -2382,32 +2382,168 @@
 tRemoteUser());%0A
+        // Deployments must be also deleted because we it is not possible to reach them after deleting DB.%0A        deleteDeployments();%0A
         deleteAl
@@ -2874,32 +2874,32 @@
 lData : data) %7B%0A
-
             data
@@ -2933,24 +2933,876 @@
    %7D%0A    %7D%0A%0A
+    @GET%0A    @Path(%22/delete-deployments%22)%0A    public void deleteDeployments() %7B%0A        LOG.warn(%22user %7B%7D is deleting all integration deploymets%22, context.getRemoteUser());%0A        List%3CIntegration%3E integrations = dataMgr.fetchAll(Integration.class).getItems();%0A        for (Integration i : integrations) %7B%0A            OpenShiftDeployment deployment = OpenShiftDeployment%0A                .builder()%0A                .name(i.getName())%0A                .token(Tokens.getAuthenticationToken())%0A                .build();%0A%0A            if (openShiftService.exists(deployment)) %7B%0A                openShiftService.delete(deployment);%0A                LOG.debug(%22Deleting integration %5C%22%7B%7D%5C%22%22, i.getName());%0A            %7D else %7B%0A                LOG.debug(%22Skipping integration named %5C%22%7B%7D%5C%22. No such deployment found.%22, i.getName());%0A            %7D%0A        %7D%0A    %7D%0A%0A
     private 

Enable to delete deployments