/*
 * Copyright 2019 the original author or authors.
 *
 * 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 org.springframework.cloud.dataflow.autoconfigure.local;

import java.util.Arrays;
import java.util.ServiceLoader;

import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.cloud.dataflow.server.config.CloudProfileProvider;
import org.springframework.context.ApplicationListener;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;

/**
 * Sets an active Spring profile of "local" when determined the current DataFlow instance
 * is a local server.
 *
 * @author Chris Schaefer
 */
public class LocalProfileApplicationListener
		implements ApplicationListener<ApplicationEnvironmentPreparedEvent>, Ordered {

	private ConfigurableEnvironment environment;

	@Override
	public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
		this.environment = event.getEnvironment();

		Iterable<CloudProfileProvider> cloudProfileProviders = ServiceLoader.load(CloudProfileProvider.class);
		boolean addedCloudProfile = false;
		for (CloudProfileProvider cloudProfileProvider : cloudProfileProviders) {
			if (cloudProfileProvider != null) {
				if (cloudProfileProvider.isCloudPlatform(environment)) {
					String profileToAdd = cloudProfileProvider.getCloudProfile();
					if (!Arrays.asList(environment.getActiveProfiles()).contains(profileToAdd)) {
						environment.addActiveProfile(profileToAdd);
						addedCloudProfile = true;
					}
				}
			}
		}
		if (!addedCloudProfile) {
			environment.addActiveProfile("local");
		}

	}


	@Override
	public int getOrder() {
		return 0;
	}
}

@@ -1157,22 +1157,39 @@
  is 
+not running on 
 a 
+c
 lo
-cal server
+ud platform
 .%0A *
@@ -1215,16 +1215,40 @@
 chaefer%0A
+ * @author Mark Pollack%0A
  */%0Apubl
@@ -1773,48 +1773,8 @@
 ) %7B%0A
-%09%09%09if (cloudProfileProvider != null) %7B%0A%09
 %09%09%09i
@@ -1825,25 +1825,24 @@
 ronment)) %7B%0A
-%09
 %09%09%09%09String p
@@ -1895,17 +1895,16 @@
 file();%0A
-%09
 %09%09%09%09if (
@@ -1982,17 +1982,16 @@
  %7B%0A%09%09%09%09%09
-%09
 environm
@@ -2031,17 +2031,16 @@
 );%0A%09%09%09%09%09
-%09
 addedClo
@@ -2061,15 +2061,8 @@
 ue;%0A
-%09%09%09%09%09%7D%0A
 %09%09%09%09
@@ -2151,13 +2151,12 @@
 %09%7D%0A%0A
+
 %09%7D%0A%0A
-%0A
 %09@Ov

clean up iterator in LocalProfileApplicationListener