import com.urbancode.air.*
import com.urbancode.commons.fileutils.FileUtils

private void removeViewPrivateFilesFunction(String fileName, File workDirFile, commandPath) {
    if (fileName != null && fileName.trim().length() > 0) {
        File file = new File(workDirFile, fileName);
        if (file.exists()) {
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            //------------------------------------------------------------------------------
            // GET THE VIEW PRIVATE FILES FOR THE PATH
            //------------------------------------------------------------------------------

            def cmdArgs = [commandPath, 'ls', '-recurse', '-view_only', '-visible', fileName];
            def comHelp = new CommandHelper(workDirFile);

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            comHelp.runCommand("Getting view-private files.", cmdArgs) { proc ->
                proc.out.close() // close stdin
                proc.waitForProcessOutput(out, System.out) // forward stdout and stderr
            }

            // read the output and delete each file
            StringTokenizer tokenizer = new StringTokenizer(out.toString(), "\n\r\f");
            while (tokenizer.hasMoreTokens()) {
                String line = tokenizer.nextToken();
                if (line != null && line.trim().length() > 0) {
                    File fileToDelete = new File(workDirFile, line.trim());
                    if (fileToDelete.exists()) {
                        boolean successfulDelete = false;
                        successfulDelete = FileUtils.deleteFileSafely(fileToDelete);
                        if (successfulDelete) {
                            System.out.println("Deleted: " + line);
                        }
                        else {
                            System.out.println("Could not delete: " + line);
                        }
                    }
                    else {
                        System.out.println("File does not exist: " + fileToDelete.getPath());
                    }
                }
            }
        }
        else {
            System.out.println("File for ${fileName} not found.");
        }
    }
}

def ch = new CommandHelper(new File('.'));
def apTool = new AirPluginTool(args[0], args[1])
def props = apTool.getStepProperties();

def commandPath = props['source/repo/commandPath'];
def removeViewPrivateFiles = Boolean.valueOf(props['source/deleteDuringCleanup']);
def viewPath = props['source/storageDir'];
def vobTagRoot = props['source/tagRoot'] ?: "";
def strategy = props['source/strategy'];
File workDirFile = null;
String[] loadRuleTemp = props['source/loadRules'].split('\n');
def loadRuleList = new ArrayList<String[]>();
def useTags = Boolean.valueOf(props['source/useTags']);
def viewName = props['source/viewName'];

loadRuleTemp.each { loadRule ->
    int i=0;
    String [] tempLoadRuleArray = loadRule.split(':');
    String [] loadRuleArray = new String[4];
    for (i=0; i<tempLoadRuleArray.length && i < 4; i++) {
      loadRuleArray[i] = tempLoadRuleArray[i];
    }
    for (i; i < 4; i++ ) {
      loadRuleArray[i] = null;
    }
    loadRuleList << loadRuleArray;
}


if (viewPath == null || viewPath.trim().length() == 0) {
    throw new IllegalStateException("View path does is not configured.");
}

if (commandPath == null || commandPath.trim().length() == 0) {
    commandPath = "cleartool";
}

if ("alreadyExists".equals(strategy)) {
    workDirFile = new File(viewPath);
    if (!workDirFile.exists()) {
        throw new IllegalStateException("View Path does not exist: " + viewPath);
    }
}
else {
    workDirFile = new File(viewName).getAbsoluteFile();
}

if (loadRuleList == null || loadRuleList.size() == 0) {
    throw new IllegalStateException("No load rules configured!");
}

//check if we are to cleanup all viewlocal files
if (removeViewPrivateFiles) {
    loadRuleList.each { loadRule ->
        String fileName = loadRule[1]
        if (fileName == null || "null".equalsIgnoreCase(fileName)) {
            fileName = ""
        }
        if (apTool.isWindows && vobTagRoot) {
            fileName = vobTagRoot + File.separator + fileName
        }

        System.out.println("Removing private files for ${fileName}");
        removeViewPrivateFilesFunction(fileName, workDirFile, commandPath);
        if (useTags) {
            //need to remove the viewName tag
            //
            def cmdArgs = [commandPath, 'rmtag', '-view', viewName];
            try {
                ch.runCommand("Removing tag " + viewName, cmdArgs)
            }
            catch (Exception e) {
                System.out.println("Failed to remove tag from clearcase!");
            }
        }
    }
}
else {
    println "Nothing to do since Remove View Private Files is set to false!"
}
