/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2022 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * 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.jboss.installer.postinstall.task;

import org.apache.commons.io.IOUtils;
import org.eclipse.jgit.api.Git;
import org.jboss.installer.auto.InstallationDataSerializer;
import org.jboss.installer.core.FileUtils;
import org.jboss.installer.core.InstallationData;
import org.jboss.installer.postinstall.TaskPrinter;
import org.jboss.installer.test.utils.MockLanguageUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import java.io.File;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.Optional;

import static org.assertj.core.api.Assertions.assertThat;
import static org.jboss.installer.postinstall.task.QuickstartsTask.PROFILE_ID_EXPRESSION;
import static org.jboss.installer.screens.QuickstartsMavenRepositorySetupScreen.DEFAULT_MAVEN_REPOSITORY;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class QuickstartsTaskTest {

    public static final String REPOSITORY_URL_EXPRESSION = "/settings/profiles/profile/repositories/repository/url";
    public static final String PLUGIN_REPO_URL_EXPRESSION = "/settings/profiles/profile/pluginRepositories/pluginRepository/url";
    public static final String ACTIVE_PROFILE_EXPRESSION = "/settings/activeProfiles/activeProfile";

    @Rule
    public TemporaryFolder tempFolder = new TemporaryFolder();
    File tempFile;
    InstallationData data;
    QuickstartsTask.Config config;
    private TaskPrinter printer = new NoopPrinter();

    @Before
    public void setUp() throws Exception {
        tempFile = tempFolder.newFile("settings.xml");
        data = new InstallationData();
        config = new QuickstartsTask.Config();
    }

    @Test
    public void createDefaultSettingsXmlTest() throws Exception {
        config.setQuickstartsSettingsPath(tempFile.toString());
        config.setQuickstartsRepository(DEFAULT_MAVEN_REPOSITORY);
        data.putConfig(config);
        new QuickstartsTask().updateSettingsXmlFile(config, printer);
        assertCorrectSettingsXmlValues(tempFile, 0, config.getQuickstartsRepository());
    }

    @Test
    public void createDefaultSettingsXml_SelectedPathIsAFolder() throws Exception {
        final File testM2 = tempFolder.newFolder("test-m2");
        config.setQuickstartsSettingsPath(testM2.toString());
        config.setQuickstartsRepository(DEFAULT_MAVEN_REPOSITORY);
        data.putConfig(config);
        new QuickstartsTask().updateSettingsXmlFile(config, printer);
        assertCorrectSettingsXmlValues(new File(testM2, "settings.xml"), 0, config.getQuickstartsRepository());
    }

    @Test
    public void createDefaultSettingsXmlTest_MultiplTrailingSlash() throws Exception {
        config.setQuickstartsSettingsPath(tempFile.toString());
        config.setQuickstartsRepository(DEFAULT_MAVEN_REPOSITORY + "///");
        data.putConfig(config);
        new QuickstartsTask().updateSettingsXmlFile(config, printer);
        final String expectedUrl = config.getQuickstartsRepository();
        assertCorrectSettingsXmlValues(tempFile, 0, DEFAULT_MAVEN_REPOSITORY);
    }

    @Test
    public void createDefaultSettingsXml_ConvertLocalPathToUrl_MultipleTrailingSlash() throws Exception {
        config.setQuickstartsSettingsPath(tempFile.toString());
        final File localRepoPath = tempFolder.newFolder("test-repo");
        config.setQuickstartsRepository(localRepoPath.getPath() + File.separator + File.separator);
        data.putConfig(config);
        new QuickstartsTask().updateSettingsXmlFile(config, printer);
        assertCorrectSettingsXmlValues(tempFile, 0, localRepoPath.toURI().toString());
    }

    @Test
    public void createDefaultSettingsXml_ConvertLocalPathToUrl_TrailingSlash() throws Exception {
        config.setQuickstartsSettingsPath(tempFile.toString());
        final File localRepoPath = tempFolder.newFolder("test-repo");
        config.setQuickstartsRepository(localRepoPath.getPath() + File.separator);
        data.putConfig(config);
        new QuickstartsTask().updateSettingsXmlFile(config, printer);
        assertCorrectSettingsXmlValues(tempFile, 0, localRepoPath.toURI().toString());
    }

    @Test
    public void createDefaultSettingsXml_ConvertLocalPathToUrl_RemoveTrailingSlash() throws Exception {
        config.setQuickstartsSettingsPath(tempFile.toString());
        final File localRepoPath = tempFolder.newFolder("test-repo");
        config.setQuickstartsRepository(localRepoPath.getPath());
        data.putConfig(config);
        new QuickstartsTask().updateSettingsXmlFile(config, printer);
        final String expectedUrl = localRepoPath.toURI().toString();
        assertCorrectSettingsXmlValues(tempFile, 0, expectedUrl.substring(0, expectedUrl.length() - 1));
    }

    @Test
    public void updateExistentSettingsXmlTest() throws Exception {
        config.setQuickstartsSettingsPath(tempFile.toString());
        config.setQuickstartsRepository(DEFAULT_MAVEN_REPOSITORY);
        data.putConfig(config);
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("default_settings.xml");
        org.apache.commons.io.FileUtils.copyInputStreamToFile(inputStream, tempFile);
        new QuickstartsTask().updateSettingsXmlFile(config, printer);
        assertThat(tempFile)
                .hasContent(org.apache.commons.io.IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("default_settings.xml"), StandardCharsets.UTF_8));
    }

    @Test
    public void updateExistentSettingsXmlWithoutRepositoryTest() throws Exception {
        config.setQuickstartsSettingsPath(tempFile.toString());
        config.setQuickstartsRepository(DEFAULT_MAVEN_REPOSITORY);
        data.putConfig(config);
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("default_settings.xml");
        final String settingsXml = IOUtils.toString(inputStream, StandardCharsets.UTF_8)
                .replaceAll("<url>https://maven.repository.redhat.com/ga/</url>", "<url>https://foo.bar</url>");
        org.apache.commons.io.FileUtils.writeStringToFile(tempFile, settingsXml, StandardCharsets.UTF_8);
        new QuickstartsTask().updateSettingsXmlFile(config, printer);
        assertCorrectSettingsXmlValues(tempFile, 1, config.getQuickstartsRepository());
    }

    @Test
    public void testSerializeConfig() throws Exception {
        config.setQuickstartsSettingsPath(tempFile.toString());
        config.setQuickstartsRepository(DEFAULT_MAVEN_REPOSITORY);
        data.putConfig(config);

        final InstallationDataSerializer serializer = new InstallationDataSerializer(new MockLanguageUtils());
        final Path outputFile = tempFolder.newFile().toPath();
        serializer.serialize(data, outputFile);

        final QuickstartsTask.Config deserializedConfig = serializer.deserialize(outputFile, Optional.empty()).getConfig(QuickstartsTask.Config.class);

        assertEquals(config, deserializedConfig);
    }

    @Test
    public void testCreateSettingsFileIfParentDoesNotExist() throws Exception {
        final File path = tempFolder.newFolder().toPath().resolve("idontexist").resolve("metoo").resolve("settings.xml").toFile();
        config.setQuickstartsSettingsPath(path.toString());
        config.setQuickstartsRepository(DEFAULT_MAVEN_REPOSITORY);
        data.putConfig(config);
        new QuickstartsTask().updateSettingsXmlFile(config, printer);
        assertCorrectSettingsXmlValues(path, 0, config.getQuickstartsRepository());
    }

    @Test
    public void checkoutIntoTargetFolder() throws Exception {
        final File path = tempFolder.newFolder().toPath().resolve("settings").resolve("settings.xml").toFile();

        final Path targetFolder = tempFolder.newFolder("target-folder").toPath();
        final File sourceRepo = tempFolder.newFolder("source-repo.git");
        Git.init().setGitDir(sourceRepo).call().close();

        config.setQuickstartsSettingsPath(path.toString());
        config.setQuickstartsRepository(DEFAULT_MAVEN_REPOSITORY);
        config.setQuickstartsGithubRepo(sourceRepo.toURI().toString());
        config.setQuickstartsGithubBranch("master");
        config.setQuickstartsTargetFolder(targetFolder.resolve("jboss-eap-quickstarts").toString());
        data.putConfig(config);
        assertTrue(new QuickstartsTask().applyToInstallation(data, printer));

        assertThat(targetFolder.resolve("jboss-eap-quickstarts"))
                .exists();
    }

    private void assertCorrectSettingsXmlValues(File file, int itemNumber, String quickstartsRepository) throws Exception {
        Document doc = FileUtils.loadXmlFromFile(file);
        XPathFactory xpathfactory = XPathFactory.newInstance();
        XPath xPath = xpathfactory.newXPath();

        NodeList profileId = (NodeList) xPath.compile(PROFILE_ID_EXPRESSION).evaluate(
                doc, XPathConstants.NODESET);
        NodeList repoUrl = (NodeList) xPath.compile(REPOSITORY_URL_EXPRESSION).evaluate(
                doc, XPathConstants.NODESET);
        NodeList pluginRepoUrl = (NodeList) xPath.compile(PLUGIN_REPO_URL_EXPRESSION).evaluate(
                doc, XPathConstants.NODESET);
        NodeList activeProfile = (NodeList) xPath.compile(ACTIVE_PROFILE_EXPRESSION).evaluate(
                doc, XPathConstants.NODESET);

        Assert.assertEquals(profileId.item(itemNumber).getTextContent(), activeProfile.item(itemNumber).getTextContent());
        Assert.assertEquals(quickstartsRepository, pluginRepoUrl.item(itemNumber).getTextContent());
        Assert.assertTrue(profileId.item(itemNumber).getTextContent().contains("jboss-ga"));
        Assert.assertEquals(itemNumber != 0, !profileId.item(itemNumber).getTextContent().equals("jboss-ga"));
        Assert.assertEquals(quickstartsRepository, repoUrl.item(itemNumber).getTextContent());
    }

}
