package com.commercehub.gradle.plugin.avro;

import org.apache.avro.compiler.specific.SpecificCompiler;
import org.apache.commons.io.FilenameUtils;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCollection;
import org.gradle.api.tasks.TaskAction;

import java.io.File;
import java.io.IOException;

public class GenerateAvroJavaTask extends OutputDirTask {
    @TaskAction
    protected void process() {
        boolean didWork = false;
        FileCollection sourceFiles = getInputs().getSourceFiles();
        getLogger().info("Found {} files", sourceFiles.getFiles().size());
        for (File sourceFile : sourceFiles) {
            getLogger().info("Processing {}", sourceFile);
            String extension = FilenameUtils.getExtension(sourceFile.getName());
            if (Constants.PROTOCOL_EXTENSION.equals(extension)) {
                processProtoFile(sourceFile);
                didWork = true;
            } else if (Constants.SCHEMA_EXTENSION.equals(extension)) {
                processSchemaFile(sourceFile);
                didWork = true;
            } else {
                throw new GradleException(String.format("Unsupported file extension: %s for %s", extension, sourceFile));
            }
        }
        setDidWork(didWork);
    }

    private void processProtoFile(File sourceFile) {
        try {
            SpecificCompiler.compileProtocol(sourceFile, getOutputDir());
        } catch (IOException ex) {
            throw new GradleException(String.format("Failed to compile protocol definition file %s", sourceFile), ex);
        }
    }

    private void processSchemaFile(File sourceFile) {
        try {
            SpecificCompiler.compileSchema(sourceFile, getOutputDir());
        } catch (IOException ex) {
            throw new GradleException(String.format("Failed to compile schema definition file %s", sourceFile), ex);
        }
    }
}

@@ -38,16 +38,80 @@
 .avro;%0A%0A
+import org.apache.avro.Protocol;%0Aimport org.apache.avro.Schema;%0A
 import o
@@ -161,16 +161,16 @@
 mpiler;%0A
-
 import o
@@ -436,16 +436,73 @@
 rTask %7B%0A
+    private Schema.Parser parser = new Schema.Parser();%0A%0A
     @Tas
@@ -1457,32 +1457,92 @@
 %7B%0A        try %7B%0A
+            Protocol protocol = Protocol.parse(sourceFile);%0A
             Spec
@@ -1557,24 +1557,93 @@
 iler
-.c
+ compiler = new SpecificC
 ompile
-P
+r(p
 rotocol
+);%0A            compiler.compileToDestination
 (sou
@@ -1899,32 +1899,86 @@
 %7B%0A        try %7B%0A
+            Schema schema = parser.parse(sourceFile);%0A
             Spec
@@ -1993,22 +1993,91 @@
 iler
-.
+ 
 compile
-Schema
+r = new SpecificCompiler(schema);%0A            compiler.compileToDestination
 (sou

use logic from avro-tools SpecificCompilerTool