/*
* 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.accuwork

import com.urbancode.air.ExitCodeException

public class ChangeStatus extends AccuworkBase {
    
    //**************************************************************************
    // CLASS
    //**************************************************************************

    //**************************************************************************
    // INSTANCE
    //**************************************************************************
    List<String> bugIdList
    String status
    boolean usingChangeSets = false;
    
    public void execute() {
        boolean error = false;
        
        login()
        
        try {
            usingChangeSets = bugIdList ? bugIdList.isEmpty() : true
            if (usingChangeSets) {
                String changesXml = getChangeSetXml()
                parseChangeSets(changesXml)
                
                if (!changes.isEmpty()) {
                    for (FileChange change : changes) {
                        def root = queryDB(null, change)
                        String xml = genXml(root)
                        sendXml(change.issueId, xml)
                    }
                }
                else {
                    println "No issues found"
                }
            }
            else {
                for (String bugId : bugIdList) {
                    def root = queryDB(bugId, null)
                    String xml = genXml(root)
                    
                    // We have to parse and send xml for each bug because we don't know 
                    // what other fields may be present. Any fields that are not added to
                    // the upload will also remove them from the actual issue
                    sendXml(bugId, xml)
                }
            }
        }
        catch (ExitCodeException e) {
            println e.getMessage()
            error = true
        }
        finally {
            logout()
            
            if (error) {
                System.exit(1)
            }
        }
        
    }
    
    private def queryDB(String bugId, FileChange change) {
        // query existing bug information.
        if (usingChangeSets) {
            bugId = change.issueId
            issueDB = change.depotName
        }
        
        print("\nQuerying Information for BUG[${bugId}] from depot ${issueDB}.")
        
        ByteArrayOutputStream bouts = new ByteArrayOutputStream();
        // generate query.xml file.
        File queryFile = File.createTempFile("accurev_bugreport", "xml");
        OutputStream outs = new FileOutputStream(queryFile);
        
        String xmlString = "<queryIssue issueDB=\"" + issueDB + "\" useAlt=\"false\">1 == \"" + bugId + "\"</queryIssue>";
        outs.write(xmlString.getBytes());
        outs.close();
        
        try {
            def command = [scmCommand, "xml"]
            
            if (host) {
                command << "-H" << host
            }
            
            command << "-l" << queryFile.getAbsolutePath()
            
            ch.runCommand("Querying Database", command) { Process proc ->
                proc.out.close() // close stdin
                def out = new PrintStream(System.out, true);
                try {
                    proc.waitForProcessOutput(bouts, out) // forward stdout and stderr to autoflushing output stream
                }
                finally {
                    out.flush();
                }
                
                println bouts.toString();
            }
            
            return parseXml(bouts.toString())
        }
        finally {
            queryFile.delete();
        }
    }
    
    private def parseXml(def xml) {
        def rootNode = new XmlParser().parseText(xml)

        Node newRoot = new Node(null, "modifyIssue")
        
        NodeList nodeList = rootNode.issue
        Node parent = nodeList[0]
        
        newRoot.append(parent)
        
        List<Node> children = new ArrayList(parent.children())
        
        for (int i = 0; i < children.size(); i++) {
            Node child = children[i]
        
            if (child.name() == "transNum") {
                println "Removing transNum node"
                parent.remove(child)
            }
            
            if (child.name() == "status") {
                println "Setting status to " + status
                child.setValue(status)
            }
        }
        
        return newRoot
    }
    
    private String genXml(def root) {
        def xmlBuilder = new groovy.xml.StreamingMarkupBuilder(useDoubleQuotes: true);
        xmlBuilder.encoding = "UTF-8"
        def xmlOut = xmlBuilder.bind{
            mkp.xmlDeclaration()
            'modifyIssue'('issueDB':"$issueDB", 'useAlt':"false"){
                'issue'{
                    root.issue[0].children().each { child ->
                        String name = child.name()
                        String id = child.@fid
                        String text = child.text()
                        
                        "$name"('fid':"$id", text)
                    }
                }
            }
        }
        println xmlOut.toString()
        return xmlOut.toString()
    }
    
    private void sendXml(String bugId, String xml) {
        // generate query.xml file.
        File queryFile = File.createTempFile("accurev_bugreport", "xml");
        
        try {
            OutputStream outs = new FileOutputStream(queryFile);
            outs.write(xml.getBytes());
            outs.close()
            
            def command = [scmCommand, "xml", "-l", queryFile.getAbsolutePath()]
            ch.runCommand("Sending changes for bug " + bugId + " to issueDB " + issueDB, command)
        }
        finally {
            queryFile.delete()
        }
    }
}