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

import org.apache.commons.io.IOUtils
import org.apache.http.client.HttpClient
import org.apache.http.client.methods.HttpGet
import org.apache.http.client.methods.HttpPost
import org.apache.http.client.methods.HttpPut
import org.apache.http.client.methods.HttpRequestBase
import org.apache.http.entity.StringEntity
import org.apache.http.util.EntityUtils


import com.urbancode.air.AirPluginTool
import com.urbancode.air.plugin.rtcworkitems.RTCWorkItemHelper
import com.urbancode.air.XTrustProvider
import com.urbancode.commons.httpcomponentsutil.HttpClientBuilder


public class CheckItemStatus {

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

    //*****************************************************************************************************************
    // INSTANCE
    //*****************************************************************************************************************

    String url
    String password
    String username
    String projectName
    String workItemId
    String desiredStatus

    def etag
    def props

    public def execute() {
        HttpClientBuilder builder = new HttpClientBuilder()
        builder.setTrustAllCerts(true)
        HttpClient client = builder.buildClient()

        XTrustProvider.install()
        def rtcHelper = new RTCWorkItemHelper(props)
        def catalogurl = rtcHelper.getCatalogUrl(client)
        rtcHelper.authenticateRTCUser(catalogurl, client)
        def servicesUrl = rtcHelper.getServicesUrl(catalogurl, client)
        def workItemUrl = rtcHelper.getWorkItemUrl(servicesUrl, client)

        println ("[Action] Getting work item status...")
        def actualStatus

        def workItemXml = rtcHelper.getWorkItemByIdentifier(workItemId, workItemUrl, client, etag)
        if (!workItemXml) {
            println "Unable to find work item $workItemId"
            System.out.println()
            return false
        }

        String statusUrl = workItemXml[RTCWorkItemHelper.n_oslc_cm.ChangeRequest][RTCWorkItemHelper.n_rtc_cm.state][0].attributes()[RTCWorkItemHelper.n_rdf.'resource']
        println ("Status URL = ${statusUrl}")

        actualStatus = rtcHelper.getWorkItemStatus(statusUrl, client)
        println "[Ok] Found status: ${actualStatus}"
        return actualStatus
    }
}
