/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* (c) Copyright IBM Corporation 2012, 2014. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*/
package com.urbancode.air.plugin.scm

import com.urbancode.air.*

import java.util.Date;
import java.util.regex.Matcher
import java.text.SimpleDateFormat

public class SCMCheckout extends SCMStep {
    
    //**************************************************************************
    // CLASS
    //**************************************************************************

    //**************************************************************************
    // INSTANCE
    //**************************************************************************
    protected final def TFS_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss 'Z'")
    
    String workspaceName
    boolean createWorkspace = false
    boolean forceGet = false
    String dirOffset = "."
    String changeset
    String label
    Date date
    
    private boolean workspaceExists = false
    
    private CommandHelper ch = new CommandHelper(workDir)
    
    public void execute() {
        TFS_DATE_FORMAT.timeZone = TimeZone.getTimeZone("UTC")
        
        workspaceExists()
        if (!workspaceExists) {
            if (createWorkspace) {
                createWorkspace()
            }
            else {
                println "The workspace does not exist"
                return
            }
        }
        
        if (!dirOffset.equals(".")) {
            remapWorkspace()
        }
        
        checkout()
    }
    
    public void workspaceExists() {
        
        try {
            def findWorkspaceCommand = [scmCommand, 'workspaces', "/server:$serverUrl", workspaceName]
            if (serverUserName && serverPassword) {
                findWorkspaceCommand << "/login:$serverUserName,$serverPassword"
            }
            ch.runCommand("Find Workspace $workspaceName", findWorkspaceCommand) { proc ->
                proc.consumeProcessErrorStream(out)
                proc.outputStream.close()
                def inWorkspaceList = false
                proc.in.eachLine { line ->
                    if (line.startsWith('-------')) {
                        inWorkspaceList = true
                    }
                    else if (inWorkspaceList && line.trim().startsWith(workspaceName + ' ')) {
                        workspaceExists = true
                    }
                }
            }
        }
        catch (Exception e) {
            // we expect this if workspace does not exist
        }
    }
    
    public void createWorkspace() {
        def createWorkspaceCommand = [scmCommand, 'workspace', '/new', '/noprompt', "/server:$serverUrl", workspaceName]
        if (serverUserName && serverPassword) {
            createWorkspaceCommand << "/login:$serverUserName,$serverPassword"
        }
        ch.runCommand("Create $workspaceName workspace", createWorkspaceCommand)
    }
    
    public void remapWorkspace() {
        def remapCommand = [scmCommand, 'workfold', '/map', "/server:$serverUrl",
            "/workspace:$workspaceName", sourceLocation, workDir.canonicalPath]
            
        if (serverUserName && serverPassword) {
         remapCommand << "/login:$serverUserName,$serverPassword"
        }
        
        ch.runCommand("Re-map $workspaceName workspace", remapCommand)
    }
    
    public void checkout() {
        def getCommand = [scmCommand, 'get', sourceLocation, '/noprompt', '/recursive']
        
        if (forceGet) {
            getCommand << '/force'
        }
        
        if (changeset) {
            getCommand << "/version:C$changeset"
        }
        else if (label) {
            getCommand << "/version:L$label"
        }        
        else if (date) {
            getCommand << ('/version:D' + TFS_DATE_FORMAT.format(date))
        }
        
        if (serverUserName && serverPassword) {
           getCommand << "/login:$serverUserName,$serverPassword"
        }
        
        ch.runCommand('Get Source', getCommand)
    }
}