#!/usr/bin/python3
#
# This script stores the image of a camera in a sequencer
#
# Usage:
#	save-image [sequencer device] [ccd device] [image attribute]
#
# Example:
# 	save-image.py seq/save/mscrccd_ref_20gev_b1.1 sr/diagnostics/ccd_srpm.01 Image8
#


from tango import *
import time, datetime 
import sys, os


def main():

	try:
		# connect to devices
		gof_dev = DeviceProxy('ecgofmasa5/gmbf/0')
		dcct=DeviceProxy('sr/diagnostics/dcct_s4')

		# get date	
		today = datetime.date.today()
		# get time
		obj_now = datetime.datetime.now()
		# format date-time
		date_save = today.strftime("%Y-%m-%d") + '-' + str(obj_now.hour) + '-' + str(obj_now.minute) + '-' + str(obj_now.second) 
		# get machine energy
		energy="{:.0f}Gev".format(dcct.Energy*10)
		filename = "resp_mat_direct_horver_" + energy + "_" + date_save + ".itpp"
		path = "/runtime/site/ecgofmasa5/etc/"
		# full path filename
		path_filename = path + filename
		
		# store the response matrix in the gof master filesystem
		gof_dev.command_inout("StoreRmGof",path_filename)
		
		# connect to database
		db = Database()
		
		# get current rm file
		rm_file = db.get_property("Gof","RespMatrixFile")
		rm_file_list = rm_file['RespMatrixFile']

		# get back rm file list
		bck_rm_files=db.get_property("Gof","RespMatrixFileBck")
		bck_rm_files_list = bck_rm_files["RespMatrixFileBck"]
		
		# append current rm file as the last element of the backup list
		bck_rm_files_list.append(rm_file_list[0])
		# create a dictionary and store it in the backup list
		bck_rm_files_list_new = {"RespMatrixFileBck":bck_rm_files_list} 
		db.put_property("Gof",bck_rm_files_list_new)

		# store the new response matrix as the default response matrix
		rm_files_list_new = {"RespMatrixFile":[path_filename]} 
		db.put_property("Gof",rm_files_list_new)

	except:
		print("Error saving gof default response matrix")
		sys.exit(1)
		
	sys.exit(0)
			
			
	
if __name__ == '__main__':
	main()