package org.jboss.pnc.buildjob;

import org.apache.maven.scm.command.checkout.CheckOutScmResult;
import org.jboss.pnc.source_manager.SCMRepositoryType;
import org.jboss.pnc.source_manager.ScmRetriever;
import org.jboss.pnc.spi.builddriver.BuildDriverStatus;

import java.io.*;
import java.util.function.Consumer;

/**
 * Created by aabulawi on 24/06/15.
 */
public class LocalBuildJob {

    private String scmUrl;
    private String outputDir;
    private final String buildScriptName = "pnc-build-script.sh";
    private String buildScriptContents;
    private String revision;
    private String buildLog = "";

    public LocalBuildJob(String scmUrl, String revision, String outputDir, String installScript) {
        this.scmUrl = scmUrl;
        this.revision = revision;
        this.outputDir = outputDir;
        this.buildScriptContents = installScript;
    }

    public void start(Consumer<BuildDriverStatus> onMonitorComplete,
                      Consumer<Exception> onMonitorError) {
        BuildDriverStatus status = BuildDriverStatus.SUCCESS;
        ScmRetriever scmRetriever = new ScmRetriever(SCMRepositoryType.GIT);

        try {
            CheckOutScmResult result = scmRetriever.cloneRepository(scmUrl, revision, outputDir);
            if (!result.isSuccess()){
                status = BuildDriverStatus.FAILED;
            }
        } catch (Exception e) {
            status = BuildDriverStatus.FAILED;
        }

        if (status.equals(BuildDriverStatus.SUCCESS)) {
            String pathToBuildScript = String.format("%s/%s/%s", System.getProperty("user.dir"), outputDir, buildScriptName);
            File buildScriptFile = new File(pathToBuildScript);
            createBuildScript(buildScriptFile, buildScriptContents);

            String[] buildcommands = {buildScriptFile.getAbsolutePath()};
            ProcessBuilder buildProcessBuilder = new ProcessBuilder(buildcommands);
            buildProcessBuilder.directory(buildScriptFile.getParentFile());

            Process process;
            try {
                process = buildProcessBuilder.start();
                boolean running = true;

                BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
                writer.newLine();
                writer.flush();
                Thread b = new Thread(new Runnable() {
                    public void run() {
                        try {
                            String line;

                            while ((line = reader.readLine()) != null) {
                                System.out.println(line);
                                buildLog += line + "\n";
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
                b.start();
                b.join();

                while (running) {
                    try {

                        process.waitFor();
                        running = false;
                    } catch (InterruptedException e) {
                        process.destroy();
                        status = BuildDriverStatus.ABORTED;
                    }
                }
            } catch (IOException e) {
                status = BuildDriverStatus.FAILED;
            } catch (InterruptedException e) {
                status = BuildDriverStatus.ABORTED;            }
        }

        onMonitorComplete.accept(status);
    }

    private void createBuildScript(File buildScriptFile, String buildScript){

        if (!buildScriptFile.exists()){
            try {
                buildScriptFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try(FileWriter fw = new FileWriter(buildScriptFile)) {
            fw.write("#!/bin/bash\n");
            for (String line : buildScript.split("\n")){
                fw.write(line+"\n");
            }
            fw.flush();
            buildScriptFile.setExecutable(true);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String getBuildLog(){
        return buildLog;
    }
}

@@ -504,16 +504,67 @@
 pt.sh%22;%0A
+    private final String buildLogName = %22mvn.log%22;%0A
     priv
@@ -1561,173 +1561,70 @@
     
-String pathToBuildScript = String.format(%22%25s/%25s/%25s%22, System.getProperty(%22user.dir%22), outputDir, buildScriptName);%0A            File buildScriptFile = new File(pathToB
+File buildScriptFile = new File(outputDir + File.separator + b
 uild
@@ -1629,16 +1629,20 @@
 ldScript
+Name
 );%0A     
@@ -1945,52 +1945,343 @@
 );%0A%0A
-            Process process;%0A            try
+%0A            File mvnlog = new File(outputDir+ File.separator + buildLogName);%0A            try %7B%0A                mvnlog.createNewFile();%0A            %7D catch (IOException e) %7B%0A                e.printStackTrace();%0A            %7D%0A%0A            Process process;%0A            try(BufferedWriter bw = new BufferedWriter(new FileWriter(mvnlog)))
  %7B%0A 
@@ -2955,24 +2955,79 @@
 ntln(line);%0A
+                                bw.write(line + %22%5Cn%22);%0A
             
@@ -3093,32 +3093,72 @@
               %7D%0A
+                            bw.flush();%0A
                 
@@ -4268,28 +4268,32 @@
 try(
-File
+Buffered
 Writer 
-f
+b
 w = new 
 File
@@ -4284,24 +4284,43 @@
 er bw = new 
+BufferedWriter(new 
 FileWriter(b
@@ -4335,16 +4335,17 @@
 ptFile))
+)
  %7B%0A     
@@ -4343,33 +4343,33 @@
 ) %7B%0A            
-f
+b
 w.write(%22#!/bin/
@@ -4451,17 +4451,17 @@
         
-f
+b
 w.write(
@@ -4464,17 +4464,19 @@
 ite(line
-+
+ + 
 %22%5Cn%22);%0A 
@@ -4500,17 +4500,17 @@
         
-f
+b
 w.flush(

Write mvn output to file in the build dir