/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.apache.maven.surefire.report;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.maven.plugin.surefire.report.ConsoleOutputFileReporter;
import org.apache.maven.surefire.api.report.SimpleReportEntry;
import org.apache.maven.surefire.api.report.TestOutputReportEntry;
import org.apache.maven.surefire.api.report.TestSetReportEntry;
import org.apache.maven.surefire.shared.utils.io.FileUtils;
import org.junit.jupiter.api.Test;

import static java.nio.charset.StandardCharsets.US_ASCII;
import static org.apache.maven.surefire.api.report.RunMode.NORMAL_RUN;
import static org.apache.maven.surefire.api.report.TestOutputReportEntry.stdOut;
import static org.apache.maven.surefire.api.report.TestOutputReportEntry.stdOutln;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertTrue;

/**
 *
 */
public class ConsoleOutputFileReporterTest {
    /*
     * Test method for 'org.codehaus.surefire.report.ConsoleOutputFileReporter.testSetCompleted(ReportEntry report)'
     */
    @Test
    public void testFileNameWithoutSuffix() throws IOException {
        File reportDir = new File(new File(System.getProperty("user.dir"), "target"), "tmp1");
        if (Files.exists(reportDir.toPath())) {
            FileUtils.deleteDirectory(reportDir);
        }
        Files.createDirectories(reportDir.toPath());
        TestSetReportEntry reportEntry = new SimpleReportEntry(
                NORMAL_RUN, 1L, getClass().getName(), null, getClass().getName(), null);
        ConsoleOutputFileReporter reporter = new ConsoleOutputFileReporter(reportDir, null, false, null, "UTF-8");
        reporter.testSetStarting(reportEntry);
        reporter.writeTestOutput((TestOutputReportEntry) stdOut("some "));
        reporter.testSetCompleted(reportEntry);
        reporter.close();

        File expectedReportFile = new File(reportDir, getClass().getName() + "-output.txt");

        assertTrue(
                expectedReportFile.exists(),
                "Report file (" + expectedReportFile.getAbsolutePath() + ") doesn't exist");

        assertThat(FileUtils.fileRead(expectedReportFile, US_ASCII.name())).contains("some ");

        //noinspection ResultOfMethodCallIgnored
        expectedReportFile.delete();
    }

    /*
     * Test method for 'org.codehaus.surefire.report.ConsoleOutputFileReporter.testSetCompleted(ReportEntry report)'
     */
    @Test
    public void testFileNameWithSuffix() throws IOException {
        File reportDir = new File(new File(System.getProperty("user.dir"), "target"), "tmp2");
        if (Files.exists(reportDir.toPath())) {
            FileUtils.deleteDirectory(reportDir);
        }
        Files.createDirectories(reportDir.toPath());
        String suffixText = "sampleSuffixText";
        TestSetReportEntry reportEntry = new SimpleReportEntry(
                NORMAL_RUN, 1L, getClass().getName(), null, getClass().getName(), null);
        ConsoleOutputFileReporter reporter = new ConsoleOutputFileReporter(reportDir, suffixText, false, null, "UTF-8");
        reporter.testSetStarting(reportEntry);
        reporter.writeTestOutput(stdOutln(null));
        reporter.writeTestOutput(stdOutln("some "));
        reporter.testSetCompleted(reportEntry);
        reporter.close();

        File expectedReportFile = new File(reportDir, getClass().getName() + "-" + suffixText + "-output.txt");

        assertTrue(
                expectedReportFile.exists(),
                "Report file (" + expectedReportFile.getAbsolutePath() + ") doesn't exist");

        assertThat(FileUtils.fileRead(expectedReportFile, US_ASCII.name())).contains("some ");

        assertThat(expectedReportFile).hasSize(9 + 2 * System.lineSeparator().length());

        //noinspection ResultOfMethodCallIgnored
        expectedReportFile.delete();
    }

    @Test
    public void testNullReportFile() throws IOException {
        File reportDir = new File(new File(System.getProperty("user.dir"), "target"), "tmp3");
        if (Files.exists(reportDir.toPath())) {
            FileUtils.deleteDirectory(reportDir);
        }
        Files.createDirectories(reportDir.toPath());
        ConsoleOutputFileReporter reporter = new ConsoleOutputFileReporter(reportDir, null, false, null, "UTF-8");
        reporter.writeTestOutput((TestOutputReportEntry) stdOut("some text"));
        reporter.testSetCompleted(new SimpleReportEntry(
                NORMAL_RUN, 1L, getClass().getName(), null, getClass().getName(), null));
        reporter.close();

        File expectedReportFile = new File(reportDir, "null-output.txt");

        assertTrue(
                expectedReportFile.exists(),
                "Report file (" + expectedReportFile.getAbsolutePath() + ") doesn't exist");

        assertThat(FileUtils.fileRead(expectedReportFile, US_ASCII.name())).contains("some ");

        //noinspection ResultOfMethodCallIgnored
        expectedReportFile.delete();
    }

    @Test
    public void testOutputWithoutStackTraceUsesCurrentReportFile() throws IOException {
        File reportDir = new File(new File(System.getProperty("user.dir"), "target"), "tmp3-without-stack");
        if (Files.exists(reportDir.toPath())) {
            FileUtils.deleteDirectory(reportDir);
        }
        Files.createDirectories(reportDir.toPath());
        TestSetReportEntry reportEntry = new SimpleReportEntry(
                NORMAL_RUN, 1L, getClass().getName(), null, getClass().getName(), null);
        ConsoleOutputFileReporter reporter = new ConsoleOutputFileReporter(reportDir, null, false, null, "UTF-8");
        reporter.testSetStarting(reportEntry);
        reporter.writeTestOutput(new TestOutputReportEntry("some text", true, false, NORMAL_RUN, 1L, null));
        reporter.close();

        File expectedReportFile = new File(reportDir, getClass().getName() + "-output.txt");
        File nullReportFile = new File(reportDir, "null-output.txt");

        assertThat(expectedReportFile).exists();
        assertThat(FileUtils.fileRead(expectedReportFile, US_ASCII.name())).contains("some text");
        assertThat(nullReportFile).doesNotExist();

        //noinspection ResultOfMethodCallIgnored
        expectedReportFile.delete();
    }

    @Test
    public void testConcurrentAccessReportFile() throws Exception {
        File reportDir = new File(new File(System.getProperty("user.dir"), "target"), "tmp4");
        if (Files.exists(reportDir.toPath())) {
            FileUtils.deleteDirectory(reportDir);
        }
        final ConsoleOutputFileReporter reporter = new ConsoleOutputFileReporter(reportDir, null, false, null, "UTF-8");
        reporter.testSetStarting(new SimpleReportEntry(
                NORMAL_RUN, 1L, getClass().getName(), null, getClass().getName(), null));
        ExecutorService scheduler = Executors.newFixedThreadPool(10);
        List<Callable<Void>> jobs = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            jobs.add(() -> {
                reporter.writeTestOutput((TestOutputReportEntry) stdOut("some text\n"));
                return null;
            });
        }
        scheduler.invokeAll(jobs);
        scheduler.shutdown();
        reporter.close();

        File expectedReportFile =
                new File(reportDir, "org.apache.maven.surefire.report.ConsoleOutputFileReporterTest-output.txt");

        assertTrue(
                expectedReportFile.exists(),
                "Report file (" + expectedReportFile.getAbsolutePath() + ") doesn't exist");

        assertThat(FileUtils.fileRead(expectedReportFile, US_ASCII.name())).contains("some text");

        StringBuilder expectedText = new StringBuilder();
        for (int i = 0; i < 10; i++) {
            expectedText.append("some text\n");
        }

        assertThat(FileUtils.fileRead(expectedReportFile, US_ASCII.name())).isEqualTo(expectedText.toString());

        //noinspection ResultOfMethodCallIgnored
        expectedReportFile.delete();
    }
}
