#!/usr/bin/env python

import sys
import readline
import rlcompleter
import math
import time, datetime
readline.parse_and_bind("tab: complete")
from commands import *

def getPower(powStr):
	tpicalStr = powStr.split(',')
	tpicalStr[0] = tpicalStr[0].split(' ')[-1]
	tpical = []
	for element in tpicalStr:
		tpical.append(float(element))

	return tpical

def getTsys(tpi, tpihot, tpicold, tcal):
	'''Computes Tsys from measurements where the CAL is ON and OFF. Create an array with Tsys
	'''
	tsys = []
	for i in range(0,len(tpi)-1):
		ts = tpi[i]*tcal/ (tpihot[i] - tpicold[i]) 
		tsys.append(ts)
	return tsys

#def tsysToLog(tsys, index, logfile):
def tsysToLog(tsys, index, logfile, channelList):
	''' Writes Tsys in the logfile as a comment
	'''

	if len(tsys) > 0:
		tsStr = '\"tsys%d/' % index
		i = 1
		for i in range(0,len(channelList)):
			if i == 0:
				tsStr = tsStr + '%dl,%2.1f' % (channelList[i], tsys[channelList[i]])
			else:
				tsStr = tsStr + ',%dl,%2.1f' % (channelList[i], tsys[channelList[i]])
		tsStr = tsStr + '  "'
		#print tsStr
	
	process_command = 'inject_snap %s' % tsStr
	ireadout = getoutput(process_command)

def getPFBChannels(logfile):
	''' Get all channels used in PFB mode. The array is used later for calibration
	@param logfile    LOG file
	'''

	try:
		file = open(logfile,'r')
		data = file.readlines()
		file.close()
	except:
		print "Error: File '%s' not found" % fileName
		sys.exit(-1)

	flex = False
	flexLines = []
	for line in data:
		if 'dbbcform' in line:
			if 'flex' in line:
				flex = True

		if flex:
			if 'dbbctrk1' in line:
				flexLines.append(line)
			if 'dbbctrk2' in line:
				flexLines.append(line)
			if 'dbbctrk3' in line:
				flexLines.append(line)
			if 'dbbctrk4' in line:
				flexLines.append(line)
				
	#print flexLines
	if flex:
		channels = extractChannels(flexLines)
	else:
		channels = "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]"

	return channels	

def extractChannels(flexLines):
	'''
	Sets a sorted array with the channels to be used in PFB mode when using a flex mode

	@param flexLines. Array composed of lines with parameters of the form: dbbc=dbbctrkx, where x=1,2,3,4
	For example:
		dbbc=dbbctrk1=1,p-0,p-1,p-2,p-3,p-4,p-5,p-6,p-7,p-8,p-9,p-10,p-11,p-12,p-13,p-14,p-15
		dbbc=dbbctrk2=2,p-11,v1-11,p-10,v1-10,p-9,v1-9,p-8,v1-8,p-7,v1-7,p-6,v1-6,p-5,v1-5,p-4,p-4
		dbbc=dbbctrk1=3,v1-0,v1-1,v1-2,v1-3,v1-4,v1-5,v1-6,v1-7,v1-8,v1-9,v1-10,v1-11,v1-12,v1-13,v1-14,v1-15

	Returns a list with the used channels in PFB mode
	'''

	#print flexLines
	channels = []
	letter = [0,0]
	for line in flexLines:
		listCh = line.split('=')
		if listCh[-1][2:] == "v1-0,v1-1,v1-2,v1-3,v1-4,v1-5,v1-6,v1-7,v1-8,v1-9,v1-10,v1-11,v1-12,v1-13,v1-14,v1-15":
			pass
		else:
			chList = listCh[-1][2:].split(',')
			channels = []

			#coreNumber = int(listCh[-1][0])
			#letter[coreNumber] = c[0:c.find('-')]

			# Thi is a piece of crap. It should be done in a different way
			for c in chList:
				if c[0] == 'p':
					channels.append(int(c[c.find('-')+1:]))
	
	return channels

def main(args):

	# Modify TCal: Thot - Tcold
	tcal1 = 277.4
	tcal2 = 277.4
	tcal3 = 277.4
	tcal4 = 277.4

	# Get last updated file from log directory
	process_command = 'ls -rt /usr2/log/*.log'
	ireadout = getoutput(process_command)
	fileList = ireadout.split('\n')
	logfile = fileList[-1].strip()

	# Get Last 100 lines
	process_command = 'tail -n 200 %s' % (logfile)
	ireadout = getoutput(process_command)
	linesList = ireadout.split('\n')

	tpi1 = None
	tpi2 = None
	tpi3 = None
	tpi4 = None

	tpihot1 = None
	tpihot2 = None
	tpihot3 = None
	tpihot4 = None

	tpicold1 = None
	tpicold2 = None
	tpicold3 = None
	tpicold4 = None

	#print linesList

	# Loop along the log to get:
	# calon
	# caloff
	# and power statements

	cal = 'sky'
	for l in linesList:
		if 'calmm=hot' in l:
			cal = 'hot'
			#print cal
		if 'calmm=cold' in l:
			cal = 'cold'
			#print cal
		if 'calmm=off' in l:
			cal = 'sky'
			#print cal
		if 'dbbc/power/ 1' in l:
			#print cal, "dbbc/power/ 1"
			pow1Str = l
			if cal == 'hot':
				tpihot1 = getPower(pow1Str)
			elif cal == 'cold':
				tpicold1 = getPower(pow1Str)
			else:
				tpi1 = getPower(pow1Str)
		elif 'dbbc/power/ 2' in l:
			#print cal, "dbbc/power/ 2"
			pow2Str = l
			if cal == 'hot':
				tpihot2 = getPower(pow1Str)
			elif cal == 'cold':
				tpicold2 = getPower(pow1Str)
			else:
				tpi2 = getPower(pow1Str)
		elif 'dbbc/power/ 3' in l:
			pow3Str = l
			if cal == 'hot':
				tpihot3 = getPower(pow1Str)
			elif cal == 'cold':
				tpicold3 = getPower(pow1Str)
			else:
				tpi3 = getPower(pow1Str)
		elif 'dbbc/power/ 4' in l:
			pow4Str = l
			if cal == 'hot':
				tpihot4 = getPower(pow1Str)
			elif cal == 'cold':
				tpicold4 = getPower(pow1Str)
			else:
				tpi4 = getPower(pow1Str)



	if tpi1 != None and tpihot1 !=None and tpicold1 != None:
		tsys1 = getTsys(tpi1, tpihot1, tpicold1, tcal1)
		channels = getPFBChannels(logfile)
		tsysToLog(tsys1, 1, logfile, channels)

	if tpi2 != None and tpihot2 !=None and tpicold2 != None:
		tsys2 = getTsys(tpi2, tpihot2, tpicold2, tcal2)
		channels = getPFBChannels(logfile)
		tsysToLog(tsys2, 2, logfile, channels)

	if tpi3 != None and tpihot3 !=None and tpicold3 != None:
		tsys3 = getTsys(tpi3, tpihot3, tpicold3, tcal3)
		channels = getPFBChannels(logfile)
		tsysToLog(tsys3, 3, logfile, channels)

	if tpi4 != None and tpihot4 !=None and tpicold4 != None:
		tsys3 = getTsys(tpi4, tpihot4, tpicold4, tcal4)
		channels = getPFBChannels(logfile)
		tsysToLog(tsys4, 4, logfile, channels)

		 
if __name__ == "__main__":
	main(sys.argv)
