package cn.axzo.workflow.generate;

import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeSpec;

import javax.lang.model.element.Modifier;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

public class GenJavaSourceFileUtils {

    public static void genJavaSourceFile(String pathStr, String packageName, String className, List<MethodSpec> methodSpecs) {
        TypeSpec typeSpec = TypeSpec
                .interfaceBuilder(className)
                .addModifiers(Modifier.PUBLIC)
                .addMethods(methodSpecs)
                .build();
        JavaFile javaFile = JavaFile.builder(packageName, typeSpec)
                .addFileComment("--auto generated by workflow auto-gen plugin--")
                .build();
        String javaFileName = typeSpec.name + ".java";
        try {
            Path path = Paths.get(pathStr);
            File packageFolder = new File(path.toFile().getAbsolutePath());
            if (!packageFolder.exists()) {
                System.out.println("package not exists:" + path);
                return;
            }
            String javaFilePath = path.toFile().getAbsolutePath() + File.separator + javaFileName;
            System.out.println("name:" + javaFilePath);
            File sourceFile = new File(javaFilePath);
            if (!sourceFile.exists()) {
                javaFile.writeTo(packageFolder);
            } else {
                javaFile.writeTo(packageFolder);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
