/*******************************************************************************
 * Copyright (c) 2017, 2018 Red Hat, Inc.
 *
 * This program and the accompanying materials are made
 * available under the terms of the Eclipse Public License 2.0
 * which is available at https://www.eclipse.org/legal/epl-2.0/
 *
 * SPDX-License-Identifier: EPL-2.0
 *
 * Contributor:
 *     Red Hat, Inc. - initial API and implementation
 ******************************************************************************/

package org.eclipse.linuxtools.docker.integration.tests.container;

import java.io.IOException;

import org.eclipse.linuxtools.docker.integration.tests.image.AbstractImageBotTest;
import org.eclipse.linuxtools.docker.integration.tests.mock.MockUtils;
import org.eclipse.linuxtools.docker.reddeer.core.ui.wizards.ImageRunSelectionPage;
import org.eclipse.linuxtools.docker.reddeer.ui.DockerImagesTab;
import org.eclipse.linuxtools.docker.reddeer.utils.BrowserContentsCheck;
import org.eclipse.reddeer.common.wait.WaitWhile;
import org.eclipse.reddeer.eclipse.condition.ConsoleHasNoChange;
import org.eclipse.reddeer.eclipse.ui.browser.WebBrowserView;
import org.eclipse.reddeer.workbench.core.condition.JobIsRunning;
import org.junit.After;
import org.junit.Test;

public class ExposePortTest extends AbstractImageBotTest {

	private static final String CONTAINER_NAME = "test_run_uhttpd";
	private static final String EXPOSED_PORT = "80";

	@Test
	public void testExposePort() throws IOException {
		pullImage(IMAGE_UHTTPD, IMAGE_TAG_LATEST);
		DockerImagesTab imagesTab = openDockerImagesTab();
		runContainer(IMAGE_UHTTPD, IMAGE_TAG_LATEST, CONTAINER_NAME, imagesTab);
		if(mockitoIsUsed()){
			MockUtils.runContainer(DEFAULT_CONNECTION_NAME, IMAGE_UHTTPD, IMAGE_TAG_LATEST, CONTAINER_NAME);
		}
		assertPortIsAccessible(EXPOSED_PORT);
	}

	private void assertPortIsAccessible(String exposedPort) {
		WebBrowserView browserView = new WebBrowserView();
		browserView.open();
		String url = createURL(":" + exposedPort);
		if (!mockitoIsUsed()) {
			BrowserContentsCheck.checkBrowserForErrorPage(browserView, url);
		}
	}

	private void runContainer(String imageName, String imageTag, String containerName, DockerImagesTab imagesTab) {
		imagesTab.runImage(imageName + ":" + imageTag);
		ImageRunSelectionPage firstPage = new ImageRunSelectionPage(imagesTab);
		firstPage.setContainerName(containerName);
		firstPage.setPublishAllExposedPorts(false);
		firstPage.finish();
		new WaitWhile(new JobIsRunning());
		new WaitWhile(new ConsoleHasNoChange());
	}

	@Override
	@After
	public void after() {
		deleteContainerIfExists(CONTAINER_NAME);
	}

}