package com.urbancode.air.plugin.scm

import com.urbancode.air.*

import java.text.*;

public class SCMCheckout extends SCMStep {

    //**************************************************************************
    // CLASS
    //**************************************************************************

    //**************************************************************************
    // INSTANCE
    //**************************************************************************
    def revision
    def date
    def checkoutWholeVob

    public void execute() {
        setupWorkDir()
        
        if (strategy == "createOnce") {
            def exists = checkExistingView()
            if (!exists) {
                createView()
            }
        }
        else if (strategy == "alwaysCreate") {
            def exists = checkExistingView()
            if (exists) {
                removeView()
            }
            createView()
        }
        else if (strategy == "useExisting") {
            // do nothing
        }
        else {
            println "Unknown view strategy '${strategy}'"
            System.exit(1)
        }

        runCommand()
    }

    private def runCommand() {
        def command = [scmCommand]
        if (loadRules?.length() == 0) {
            populateVob(null)
        }
        else {
            loadRules.eachLine { loadRule ->
                if (checkoutWholeVob) {
                    def vob = getVobFromPath(loadRule)
                    populateVob(vob)
                }
                else {
                    loadRule = stripLeadingSlashes(loadRule)
                    populateVob(loadRule)
                }
            }
        }
    }

    private def getVobFromPath(def path) {
        def result

        // strip any / or \ at the beginning of the path
        path = stripLeadingSlashes(path)
        if (path?.length() > 0) {
            // now look for the first / or \ and strip anything after to get the name
            // of the vob.
            int index = path.indexOf('\\');
            if (index != -1) {
                result = path.substring(0, index);
            }
            else if ((index = path.indexOf('/')) != -1) {
                result = path.substring(0, index);
            }
            else {
                result = path;
            }
        }

        return result
    }
    
    private def stripLeadingSlashes(def path) {
        // strip any / or \ at the beginning of the path
        while (path.startsWith("\\") || path.startsWith("/")) {
            path = path.substring(1)
        }
        
        return path
    }
}
