/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

package com.facebook.react.codegen.generator;

import static java.nio.charset.StandardCharsets.UTF_8;

import com.facebook.react.codegen.generator.model.CodegenException;
import com.facebook.react.codegen.generator.model.TypeData;
import com.facebook.react.codegen.generator.resolver.ResolvedType;
import com.facebook.react.codegen.generator.resolver.TypeResolver;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.TypeSpec;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Given a react-native-codegen JSON schema, generate a set of .java files for React Native. The
 * generator is isolated to a single schema, and a single Java package output.
 */
public final class JavaGenerator {
  public static final String LICENSE_HEADER =
      "/*\n"
          + " * Copyright (c) Meta Platforms, Inc. and affiliates.\n"
          + " *\n"
          + " * This source code is licensed under the MIT license found in the\n"
          + " * LICENSE file in the root directory of this source tree.\n"
          + " *\n"
          + " * Generated by react-native-codegen JavaGenerator.\n"
          + " *\n"
          + " * @"
          + "generated\n"
          + " * @"
          + "nolint\n"
          + " */\n\n";
  private final File mSchemaFile;
  private final String mJavaPackageName;
  private final File mOutputDir;

  public JavaGenerator(final File schemaFile, final String javaPackageName, final File outputDir) {
    mSchemaFile = schemaFile;
    mJavaPackageName = javaPackageName;
    mOutputDir = outputDir;
  }

  public void build() throws CodegenException, FileNotFoundException, IOException {
    // Step 1: Given a schema JSON, collect all types.
    final TypeData typeData = SchemaJsonParser.parse(mSchemaFile);

    // Step 2: Resolve each type, then collect those that produce a class or interface (TypeSpec).
    final List<TypeSpec> typeSpecsToWrite =
        typeData.getAllTypes().stream()
            .map(
                t -> {
                  final ResolvedType resolvedType =
                      TypeResolver.resolveType(typeData.getType(t), typeData, false);
                  final TypeSpec spec = resolvedType.getGeneratedCode(mJavaPackageName);
                  return spec;
                })
            .filter(f -> f != null)
            .collect(Collectors.toList());

    // Step 3: Write all of the TypeSpec's into the output directory.
    for (final TypeSpec typeSpec : typeSpecsToWrite) {
      writeTypeSpecToFile(typeSpec);
    }
  }

  private final void writeTypeSpecToFile(final TypeSpec typeSpec)
      throws CodegenException, IOException {
    JavaFile file = JavaFile.builder(mJavaPackageName, typeSpec).skipJavaLangImports(true).build();

    // Instead of using JavaFile.writeTo() API, manage the output files ourselves because
    // JavaFile.addFileComment() does not support "block comment" style.
    // See https://github.com/square/javapoet/issues/682#issuecomment-512238075.
    Path outputDirPath = new File(mOutputDir, "java").toPath();

    if (Files.exists(outputDirPath) && !Files.isDirectory(outputDirPath)) {
      throw new CodegenException(
          "Output path " + outputDirPath + " exists but is not a directory.");
    }

    if (!mJavaPackageName.isEmpty()) {
      for (String packageComponent : mJavaPackageName.split("\\.")) {
        outputDirPath = outputDirPath.resolve(packageComponent);
      }
      Files.createDirectories(outputDirPath);
    }

    Path outputPath = outputDirPath.resolve(typeSpec.name + ".java");
    try (Writer writer = new OutputStreamWriter(Files.newOutputStream(outputPath), UTF_8)) {
      writer.write(LICENSE_HEADER + file.toString());
    }
  }
}
