/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* IBM UrbanCode Deploy
* IBM UrbanCode Release
* IBM AnthillPro
* (c) Copyright IBM Corporation 2016, 2017. 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.tfs

import com.microsoft.tfs.core.TFSTeamProjectCollection
import com.microsoft.tfs.core.httpclient.UsernamePasswordCredentials

public class TFSFactory {
        //--------------------------------------------------------------
    public static TFSTeamProjectCollection createTFSCollection (tfsCollectionName, tfsPassword, tfsUrl, tfsUserName) {
        TFSTeamProjectCollection result

        URI tfsURI = createURI(tfsUrl, tfsCollectionName)
        UsernamePasswordCredentials tfsCreds = getTFSCredentials(tfsPassword, tfsUserName)
        try {
            result = new TFSTeamProjectCollection(tfsURI, tfsCreds)
            result.authenticate()
        } catch (Exception ex){
            ex.printStackTrace()
            if (result) {
                result.close()
            }
            println "[Error] Unable to connect with the TFS server."
        }

        return result
    }

    //--------------------------------------------------------------
    private static URI createURI(tfsUrl, tfsCollectionName) {
        URI result

        // Trim inputted URL and Collection
        String tfsURLTrimmed = tfsUrl.trim()
        String tfsCollectionNameTrimmed = tfsCollectionName.trim()

        // Validate base URL
        URL tfsUrlValidated = new URL(tfsURLTrimmed)

        // Append collection to path
        String path = tfsUrlValidated.getPath() + "/" + tfsCollectionNameTrimmed

        // Get encoded URI with new path
        result = new URI(tfsUrlValidated.getProtocol(), null, tfsUrlValidated.getHost(), tfsUrlValidated.getPort(), path, null, null)

        return result
    }

    //--------------------------------------------------------------
    private static UsernamePasswordCredentials getTFSCredentials (tfsPassword, tfsUserName) {
        UsernamePasswordCredentials result

        // Trim inputs
        String tfsUserNameTrimmed = tfsUserName.trim()

        // Create Creds object for later use
        result = new UsernamePasswordCredentials(tfsUserNameTrimmed, tfsPassword)

        return result
    }
}
