package org.jboss.installer.screens.jsf;

import org.jboss.installer.core.MnemonicUtils;
import org.jboss.installer.core.ValidationResult;
import org.jboss.installer.postinstall.task.JsfLibraryTask;
import org.jboss.installer.postinstall.task.jsf.MyFacesJsfLibrarySetup;
import org.jboss.installer.test.utils.MavenUtils;
import org.jboss.installer.test.utils.MockLanguageUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

import java.io.File;
import java.net.URL;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;
import static org.jboss.installer.postinstall.task.jsf.MyFacesJsfLibrarySetup.MYFACES_API_ARTIFACT_ID;
import static org.jboss.installer.postinstall.task.jsf.MyFacesJsfLibrarySetup.MYFACES_GROUP_ID;
import static org.jboss.installer.screens.jsf.ExistingChannelPanel.INVALID_COORDINATE_FORMAT;
import static org.jboss.installer.screens.jsf.ExistingChannelPanel.MANIFEST_COORDINATE_LABEL_KEY;
import static org.jboss.installer.screens.jsf.ExistingChannelPanel.SOURCE_REPOSITORY_LABEL_KEY;
import static org.jboss.installer.validators.CertificateSecurityDomainValidator.GENERIC_VALIDATION_EMPTY_FIELD;
import static org.jboss.installer.validators.MavenRepositoryValidator.LOCAL_REPO_PATH_ERROR_KEY;
import static org.jboss.installer.validators.MavenRepositoryValidator.REMOTE_REPO_PATH_ERROR_KEY;
import static org.jboss.installer.validators.RepositoryContentValidator.ARTIFACT_NOT_FOUND;
import static org.junit.Assert.assertEquals;

public class ExistingChannelPanelTest {

    private static final String JSF_VERSION = "4.0.1";
    @Rule
    public TemporaryFolder temp = new TemporaryFolder();

    private MockLanguageUtils langUtils = new MockLanguageUtils();

    @Test
    public void validValues() throws Exception {
        final File channelRepository = temp.newFolder();
        final URL channelRepositoryURL = channelRepository.toURI().toURL();
        final String channelManifest = new MyFacesJsfLibrarySetup(temp.newFolder().toPath(), langUtils).createChannelManifest(JSF_VERSION, channelRepository.toPath().toString());
        MavenUtils.deployMyFacesArtifactsLocally(JSF_VERSION, MavenUtils.CENTRAL_REPOSITORY_URL, channelRepositoryURL.toExternalForm());

        final TestableExistingChannelPanel panel = new TestableExistingChannelPanel(channelRepositoryURL.toExternalForm(), channelManifest);

        final ValidationResult result = panel.validateInput();
        assertEquals(result.getMessage(), ValidationResult.Result.OK, result.getResult());

        final JsfLibraryTask.Config config = new JsfLibraryTask.Config();
        panel.populateConfig(config);

        assertEquals(channelManifest, config.getManifestCoordinates());
        assertThat(config.getRemoteMavenRepositoryUrls())
                .containsExactly(new URL(channelRepositoryURL.toExternalForm()));
        assertEquals(JsfLibraryTask.Config.JsfProject.MyFaces, config.getJsfProject());
    }

    @Test
    public void validValuesWithLocalPath() throws Exception {
        final File channelRepository = temp.newFolder();
        final URL channelRepositoryURL = channelRepository.toURI().toURL();
        final String channelManifest = new MyFacesJsfLibrarySetup(temp.newFolder().toPath(), langUtils).createChannelManifest(JSF_VERSION, channelRepository.toPath().toString());
        MavenUtils.deployMyFacesArtifactsLocally(JSF_VERSION, MavenUtils.CENTRAL_REPOSITORY_URL, channelRepositoryURL.toExternalForm());
        final TestableExistingChannelPanel panel = new TestableExistingChannelPanel(channelRepository.toString(), channelManifest);

        final ValidationResult result = panel.validateInput();
        assertEquals(result.getMessage(), ValidationResult.Result.OK, result.getResult());

        final JsfLibraryTask.Config config = new JsfLibraryTask.Config();
        panel.populateConfig(config);

        assertEquals(channelManifest, config.getManifestCoordinates());
        assertThat(config.getRemoteMavenRepositoryUrls())
                .containsExactly(channelRepositoryURL);
        assertEquals(JsfLibraryTask.Config.JsfProject.MyFaces, config.getJsfProject());
    }

    @Test
    public void nullCoordinatesReturnsError() throws Exception {
        final TestableExistingChannelPanel panel = new TestableExistingChannelPanel("https://foo.bar", null);

        final ValidationResult result = panel.validateInput();
        assertEquals(result.getMessage(), ValidationResult.Result.ERROR, result.getResult());
        assertThat(result.getMessage())
                .startsWith(GENERIC_VALIDATION_EMPTY_FIELD)
                .contains(MANIFEST_COORDINATE_LABEL_KEY);
    }

    @Test
    public void whitespaceCoordinatesReturnsError() throws Exception {
        final TestableExistingChannelPanel panel = new TestableExistingChannelPanel("https://foo.bar", "   ");

        final ValidationResult result = panel.validateInput();
        assertEquals(result.getMessage(), ValidationResult.Result.ERROR, result.getResult());
        assertThat(result.getMessage())
                .startsWith(GENERIC_VALIDATION_EMPTY_FIELD)
                .contains(MANIFEST_COORDINATE_LABEL_KEY);
    }

    @Test
    public void emptyCoordinatesReturnsError() throws Exception {
        final TestableExistingChannelPanel panel = new TestableExistingChannelPanel("https://foo.bar", "");

        final ValidationResult result = panel.validateInput();
        assertEquals(result.getMessage(), ValidationResult.Result.ERROR, result.getResult());
        assertThat(result.getMessage())
                .startsWith(GENERIC_VALIDATION_EMPTY_FIELD)
                .contains(MANIFEST_COORDINATE_LABEL_KEY);
    }

    @Test
    public void nullRepositoryReturnsError() throws Exception {
        final TestableExistingChannelPanel panel = new TestableExistingChannelPanel(Collections.emptyList(), "foo:bar");

        final ValidationResult result = panel.validateInput();
        assertEquals(result.getMessage(), ValidationResult.Result.ERROR, result.getResult());
        assertThat(result.getMessage())
                .startsWith(GENERIC_VALIDATION_EMPTY_FIELD)
                .contains(SOURCE_REPOSITORY_LABEL_KEY);
    }

    @Test
    public void whitespaceSourceRepositoryReturnsError() throws Exception {
        final TestableExistingChannelPanel panel = new TestableExistingChannelPanel("    ", "foo:bar");

        final ValidationResult result = panel.validateInput();
        assertEquals(result.getMessage(), ValidationResult.Result.ERROR, result.getResult());
        assertThat(result.getMessage())
                .startsWith(GENERIC_VALIDATION_EMPTY_FIELD)
                .contains(SOURCE_REPOSITORY_LABEL_KEY);
    }

    @Test
    public void emptySourceRepositoryReturnsError() throws Exception {
        final TestableExistingChannelPanel panel = new TestableExistingChannelPanel("", "foo:bar");

        final ValidationResult result = panel.validateInput();
        assertEquals(result.getMessage(), ValidationResult.Result.ERROR, result.getResult());
        assertThat(result.getMessage())
                .startsWith(GENERIC_VALIDATION_EMPTY_FIELD)
                .contains(SOURCE_REPOSITORY_LABEL_KEY);
    }

    @Test
    public void invalidUrlStringReturnsError() throws Exception {
        final TestableExistingChannelPanel panel = new TestableExistingChannelPanel("http://invalid", "foo:bar");

        final ValidationResult result = panel.validateInput();
        assertEquals(result.getMessage(), ValidationResult.Result.ERROR, result.getResult());
        assertThat(result.getMessage())
                .isEqualTo(REMOTE_REPO_PATH_ERROR_KEY);
    }

    @Test
    public void nonExistingRepositoryPathReturnsError() throws Exception {
        final TestableExistingChannelPanel panel = new TestableExistingChannelPanel(Path.of("i", "dont", "exist").toString(), "foo:bar");

        final ValidationResult result = panel.validateInput();
        assertEquals(result.getMessage(), ValidationResult.Result.ERROR, result.getResult());
        assertThat(result.getMessage())
                .isEqualTo(LOCAL_REPO_PATH_ERROR_KEY);
    }

    @Test
    public void incompleteChannelIsError() throws Exception {
        final File channelRepository = temp.newFolder();
        final URL channelRepositoryURL = channelRepository.toURI().toURL();
        final String channelManifest = new MyFacesJsfLibrarySetup(temp.newFolder().toPath(), langUtils).createChannelManifest(JSF_VERSION, channelRepository.toPath().toString());

        final TestableExistingChannelPanel panel = new TestableExistingChannelPanel(channelRepository.toString(), channelManifest);

        assertEquals(ValidationResult.error(langUtils.getString(ARTIFACT_NOT_FOUND, MYFACES_GROUP_ID,
                        MYFACES_API_ARTIFACT_ID, JSF_VERSION, channelRepositoryURL.toExternalForm())) ,
                panel.validateInput());
    }

    @Test
    public void manifestCoordinateDoesntContainGroupId() throws Exception {
        final TestableExistingChannelPanel panel = new TestableExistingChannelPanel(MavenUtils.CENTRAL_REPOSITORY_URL, "foo");

        assertEquals(ValidationResult.error(langUtils.getString("jsf_install.manifest_coordinate_format")), panel.validateInput());
    }

    @Test
    public void manifestCoordinateContainVersion() throws Exception {
        final TestableExistingChannelPanel panel = new TestableExistingChannelPanel(MavenUtils.CENTRAL_REPOSITORY_URL, "foo:bar:1.1");

        assertEquals(ValidationResult.error(langUtils.getString(INVALID_COORDINATE_FORMAT)), panel.validateInput());
    }

    private class TestableExistingChannelPanel extends ExistingChannelPanel {

        private List<String> sourceRepositoryValue;
        private String manifestCoordinatesValue;

        public TestableExistingChannelPanel(List<String> sourceRepositoryValue, String manifestCoordinatesValue) {
            super(langUtils, new MnemonicUtils());
            this.sourceRepositoryValue = sourceRepositoryValue;
            this.manifestCoordinatesValue = manifestCoordinatesValue;
        }

        public TestableExistingChannelPanel(String sourceRepositoryValue, String manifestCoordinatesValue) {
            super(langUtils, new MnemonicUtils());
            this.sourceRepositoryValue = List.of(sourceRepositoryValue);
            this.manifestCoordinatesValue = manifestCoordinatesValue;
        }

        @Override
        protected List<String> getSourceRepositoryValue() {
            return sourceRepositoryValue;
        }

        @Override
        protected String getManifestCoordinatesValue() {
            return manifestCoordinatesValue;
        }
    }

}