# Bo Milvang-Jensen (milvang@astro.ku.dk), 11-Jul-2018
# Test to upload a PAF file for a VIRCAM OB using ESO's Python binding p2api
# for the p2 API, see https://www.eso.org/cop/apidoc/index.html

import pprint
import p2api
help(p2api)

# get an object needed for the "pretty printing" below, e.g. p.pprint(folder)
p = pprint.PrettyPrinter(indent=4)

# "login" to the p2 test/demo account
api = p2api.ApiConnection('demo', '52052', 'tutorial')

# Side note: go to https://www.eso.org/p2demo
# create a folder called milvang_test1 under the VIRCAM run and note
# its "Container ID for obximport": 1987120
runContainerId = 1987120

# Create (sub)folder (not necessary)
folder, folderVersion = api.createFolder(runContainerId, 'test_folder1')
folderId = folder['containerId']
p.pprint(folder)

# Create OB
ob, obVersion = api.createOB(folderId, 'test_OB')
obId = ob['obId']
p.pprint(ob)

# Add acquisition template
acqTpl, acqTplVersion = api.createTemplate(obId, 'VIRCAM_img_acq_tile')
p.pprint(acqTpl)

# Add science template
scTpl, scTplVersion = api.createTemplate(obId, 'VIRCAM_img_obs_tile1')
p.pprint(scTpl)

# Add the PAF file used for VIRCAM, here file /tmp/foo.paf
templateId = scTpl['templateId']
_, version = api.getFileParam(obId, templateId, 'SEQ.REF.FILE1', '/dev/null')
api.saveFileParam(obId, templateId, 'SEQ.REF.FILE1', '/tmp/foo.paf', version)

# Check that the SEQ.REF.FILE1 parameter has been changed
tpl, tplVersion = api.getTemplate(obId, templateId)
p.pprint(tpl)
# --- the following is seen:
#                     {   'name': 'SEQ.REF.FILE1',
#                         'type': 'paramfile',
#                         'value': 'UltraVistaPaw5new-1-1_1-1.paf'},
# The name (UltraVistaPaw5new-1-1_1-1.paf) has been automatically read
# from the uploaded file (/tmp/foo.paf) from the line starting PAF.NAME
