package com.urbancode.air.plugin.scm

import com.urbancode.air.*

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

public class SCMTag extends SCMStep {
    
    //**************************************************************************
    // CLASS
    //**************************************************************************
    public final def LINE_SEPARATOR = System.getProperty('line.separator')
    
    //**************************************************************************
    // INSTANCE
    //**************************************************************************
    boolean multiLabel
    String labelMessage
    String label
    String[] depotPathArray
    
    private labelDescription = null
    private def out = System.out
    
    public void execute() {
        this.login()
        
        getLabelDescription()
        editDescription()
        saveLabel()
        applyLabel()
    }
    
    public void getLabelDescription() {
        def getLabelDescCmd = createP4BaseCommand()
        
        getLabelDescCmd << 'label' << '-o' << label
        ch.runCommand('Getting Label Description', getLabelDescCmd) { proc ->
            proc.out.close() // close stdin
            proc.consumeProcessErrorStream(out)
            labelDescription = proc.text // read the label description
        }
    }
    
    public void editDescription() {
        def modLabelDescription = new StringBuilder()
        
        labelDescription.eachLine{line ->
            modLabelDescription << line + LINE_SEPARATOR
            if (labelMessage && line.startsWith('Description: ')) {
                modLabelDescription << "\t${labelMessage}" + LINE_SEPARATOR
            }
            else if (!multiLabel && line.startsWith('View: ')) {
                for (path in depotPathArray) {
                    modLabelDescription << "\t${path}" + LINE_SEPARATOR
                }
            }
        }
        labelDescription = modLabelDescription.toString()
    }
    
    public void saveLabel() {
        def saveLabelCmd = createP4BaseCommand()
        
        saveLabelCmd << 'label' << '-i'
        ch.runCommand('Save Label', saveLabelCmd) { proc ->
            proc.consumeProcessOutput(out, out)
            proc.withWriter{ it << labelDescription } // feed in the modified label definition to the process (and close/flush stream afterwards)
        }
        
    }
    
    public void applyLabel() {
        def applyLableCmd = createP4BaseCommand()
        
        applyLableCmd << 'labelsync'
        if (multiLabel) {
            applyLableCmd << '-a'
        }
        applyLableCmd << '-l' << label
        ch.runCommand('Apply Label', applyLableCmd)
    }
}