package com.urbancode.air.plugin.scm

import com.urbancode.air.*

public class SCMStep {

    static protected final String REPO_TYPE = 'RTC'
    
    String command = "scm"
    String serverUrl
    String username
    String password
    String workspace
    String stream
    String baseline
    String snapshot
    String components
    String buildSnapshot
    String buildSnapshotDescription
    String buildSnapshotProperty = 'rtc.snapshot'
    boolean isIncludeRoot = false
    boolean isForce = false
    def listSnapshotDateFormat
    File directory
    CommandHelper cmdHelper

    public void cleanup(dir) {
        if (dir == null) {
            dir = directory.canonicalFile
        }
        println "Removing everything in ${dir}..."
        dir.listFiles().each {file ->
            boolean success = false;
            if (file.isFile()) {
                success = file.delete()
            }
            else if (file.isDirectory()) {
                success = file.deleteDir()
            }
            if (!success) {
                println("Failed to delete $file")
            }
        }
        println "Done deleting directory contents for ${dir}"
    }

    public void undo(dir) {
        if (dir == null) {
            dir = directory.canonicalFile
        }
        def statusText
        getCmdHelper().runCommand('Get workspace status', [command, '--non-interactive', 'status', '-u', username, '-P', password]) {proc ->
            proc.consumeProcessErrorStream(out)
            proc.outputStream.close()
            statusText = proc.text.trim()
            println statusText
        }
        def isChange = false
        def isWorkspaceMatch = false
        def undoCommand = []
        undoCommand << command << '--non-interactive' << 'undo' << '-u' << username << '-P' << password
        statusText.eachLine {it ->
            def line = it.trim()
            if (line.startsWith('Workspace')) {
                line.find('Workspace: \\((\\d+)\\) "(.*)" <->.*') {match, workspaceAlias, workspaceName ->
                    if (workspaceAlias.equalsIgnoreCase(workspace) || workspaceName.equalsIgnoreCase(workspace)) {
                        isWorkspaceMatch = true
                    }
                    else {
                        println "Local workspace ${workspaceAlias}:${workspaceName} does not match required remote workspace ${workspace}!"
                    }
                }
            }
            else if (line.startsWith('Unresolved')) {
                isChange = true
            }
            else if (isChange && (line.startsWith('a-') || line.startsWith('d-') || line.startsWith('m-') || line.startsWith('-c'))) {
                undoCommand << line.substring(4)
            }
            else if (isChange) {
                isChange = false
            }
        }

        //now run the undo command on all local changes unless the workspaces don't match
        if (!isWorkspaceMatch) {
            cleanup(dir)
        }
        else if (undoCommand.size() > 7) {
            getCmdHelper().runCommand('Undo local changes', undoCommand)
        }
        else {
            println 'No local changes found, nothing to cleanup!'
        }
    }

    public void repair() {
        getCmdHelper().runCommand('Attempt local workspace repair',
                [command, '--non-interactive', 'repair',
                '-r', serverUrl,
                '-u', username,
                '-P', password])
    }
    
    protected CommandHelper getCmdHelper() {
        if (!cmdHelper) {
            cmdHelper = new CommandHelper(directory)
        }
        
        return cmdHelper
    }
}
