"""
This sample demonstrates the following:
    Given a list of changelists:
    
    Create a new label
        Change the view
        Change the description
    
    Identify all the files in each Changelist
    Add the most recent version of each file in all changelists to the label

"""
import p4 as P4API

p4 = P4API.P4()
p4.parse_forms()
p4.connect()

labelName = 'P4NetTestingSample'

# build my label
labelForm = p4.fetch_label(labelName)
labelForm['Description'] = 'Created for P4.Net sample'
view = ['//guest/shawn_hladky/...']
labelForm['View'] = view
p4.save_label(labelForm)


# My list of changes.  This is totally arbitrary
changes=['5774', '5680', '5636', '5444']

# sort ascending, so the highest revisions will be last when looping
sorted_changes = changes.sort()

# dictionary: keyed by file, value = revision
filerevs = {}

# spin the description on each file
for chg in p4.run_describe('-s', *changes):
    depotFiles = chg['depotFile']
    revisions  = chg['rev']
    for i in range(0, len(depotFiles)):
        key,value = depotFiles[i], revisions[i]
        filerevs[key]=value

# convert the dictionary to a list like ['//depot/file#5']
fileRevList = ["%s#%s" % (k,v) for k,v in filerevs.items()]

# print fileRevList

# now I want to run in non-parsed mode
p4.disconnect()
p4 = P4API.P4()
p4.connect()

labelsync_output = p4.run('labelsync', '-l', labelName, *fileRevList)

for s in labelsync_output: print s

# delete the label to keep the public depot clean :-)
p4.run('label', '-d', labelName)

p4.disconnect()