/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * license agreements; and to You under the Apache License, version 2.0:
 *
 *   https://www.apache.org/licenses/LICENSE-2.0
 *
 * This file is part of the Apache Pekko project, which was derived from Akka.
 */

/*
 * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
 */

package docs.javadsl;

import org.apache.pekko.NotUsed;
import org.apache.pekko.actor.ActorSystem;
import org.apache.pekko.japi.Pair;
// #walk
// #ls
import org.apache.pekko.stream.Materializer;
import org.apache.pekko.stream.connectors.file.javadsl.Directory;
// #ls
import java.nio.file.FileVisitOption;
// #walk
import org.apache.pekko.stream.connectors.testkit.javadsl.LogCapturingExtension;
import org.apache.pekko.stream.javadsl.Flow;
import org.apache.pekko.stream.javadsl.FlowWithContext;
import org.apache.pekko.stream.javadsl.Sink;
import org.apache.pekko.stream.javadsl.Source;
import org.apache.pekko.stream.testkit.javadsl.StreamTestKit;
import org.apache.pekko.testkit.javadsl.TestKit;
import com.google.common.jimfs.Configuration;
import com.google.common.jimfs.Jimfs;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.extension.ExtendWith;

import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.TimeUnit;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

@ExtendWith(LogCapturingExtension.class)
public class DirectoryTest {

  private static ActorSystem system;

  @BeforeAll
  public static void beforeAll() throws Exception {
    system = ActorSystem.create();
  }

  @AfterAll
  public static void afterAll() throws Exception {
    TestKit.shutdownActorSystem(system);
  }

  private FileSystem fs;

  @BeforeEach
  public void setup() {
    fs = Jimfs.newFileSystem(Configuration.unix());
  }

  @Test
  public void listFiles() throws Exception {
    final Path dir = fs.getPath("listfiles");
    Files.createDirectories(dir);
    final Path file1 = Files.createFile(dir.resolve("file1"));
    final Path file2 = Files.createFile(dir.resolve("file2"));

    // #ls

    final Source<Path, NotUsed> source = Directory.ls(dir);
    // #ls

    final List<Path> result =
        source.runWith(Sink.seq(), system).toCompletableFuture().get(3, TimeUnit.SECONDS);
    assertEquals(result.size(), 2);
    assertEquals(result.get(0), file1);
    assertEquals(result.get(1), file2);
  }

  @Test
  public void walkAFileTree() throws Exception {
    final Path root = fs.getPath("walk");
    Files.createDirectories(root);
    final Path subdir1 = root.resolve("subdir1");
    Files.createDirectories(subdir1);
    final Path file1 = subdir1.resolve("file1");
    Files.createFile(file1);
    final Path subdir2 = root.resolve("subdir2");
    Files.createDirectories(subdir2);
    final Path file2 = subdir2.resolve("file2");
    Files.createFile(file2);

    // #walk

    final Source<Path, NotUsed> source = Directory.walk(root);
    // #walk

    final List<Path> result =
        source.runWith(Sink.seq(), system).toCompletableFuture().get(3, TimeUnit.SECONDS);
    assertEquals(result, List.of(root, subdir1, file1, subdir2, file2));
  }

  @Test
  public void walkAFileTreeWithOptions() throws Exception {
    final Path root = fs.getPath("walk2");
    Files.createDirectories(root);
    final Path subdir1 = root.resolve("subdir1");
    Files.createDirectories(subdir1);
    final Path file1 = subdir1.resolve("file1");
    Files.createFile(file1);
    final Path subdir2 = root.resolve("subdir2");
    Files.createDirectories(subdir2);
    final Path file2 = subdir2.resolve("file2");
    Files.createFile(file2);

    // #walk

    final Source<Path, NotUsed> source = Directory.walk(root, 1, FileVisitOption.FOLLOW_LINKS);
    // #walk

    final List<Path> result =
        source.runWith(Sink.seq(), system).toCompletableFuture().get(3, TimeUnit.SECONDS);
    assertEquals(result, List.of(root, subdir1, subdir2));
  }

  @Test
  public void createDirectories() throws Exception {
    Path dir = fs.getPath("mkdirsJavadsl");
    Files.deleteIfExists(dir);
    Files.createDirectories(dir);
    // #mkdirs
    Flow<Path, Path, NotUsed> flow = Directory.mkdirs();

    CompletionStage<List<Path>> created =
        Source.from(List.of(dir.resolve("dirA"), dir.resolve("dirB")))
            .via(flow)
            .runWith(Sink.seq(), system);
    // #mkdirs

    final List<Path> result = created.toCompletableFuture().get(3, TimeUnit.SECONDS);
    assertTrue(Files.isDirectory(result.get(0)));
    assertTrue(Files.isDirectory(result.get(1)));
  }

  @Test
  public void createDirectoriesWithContect() throws Exception {
    Path dir = fs.getPath("mkdirsWithContextJavadsl");
    Files.deleteIfExists(dir);
    Files.createDirectories(dir);
    // #mkdirs

    FlowWithContext<Path, SomeContext, Path, SomeContext, NotUsed> flowWithContext =
        Directory.mkdirsWithContext();
    // #mkdirs
    CompletionStage<List<Path>> created =
        Source.from(List.of(dir.resolve("dirA"), dir.resolve("dirB")))
            .asSourceWithContext(ctx -> new SomeContext())
            .via(flowWithContext)
            .asSource()
            .map(Pair::first)
            .runWith(Sink.seq(), system);

    final List<Path> result = created.toCompletableFuture().get(3, TimeUnit.SECONDS);
    assertTrue(Files.isDirectory(result.get(0)));
    assertTrue(Files.isDirectory(result.get(1)));
  }

  @AfterEach
  public void tearDown() throws Exception {
    fs.close();
    fs = null;
    StreamTestKit.assertAllStagesStopped(Materializer.matFromSystem(system));
  }

  static class SomeContext {}
}
