#! /usr/bin/env python
from os.path import abspath
from FAHBaseType import FAHBaseType
from FAHJob import FAHJob
type0 = 0
type1 = 1
class Error:
	def __init__(self, name, type, index):
		if (type == type0):
			self.getPRCG = self.get0
		elif (type == type1):
			self.getPRCG = self.get1
		self.name = name
		self.index = index

	def get0(self, pattern):
		prcg = pattern.split()[self.index]
		(p, r, g, c,) = prcg[1:-1].split(',')
		return (int(p), int(r), int(c), int(g))

	def get1(self, pattern):
		parts = pattern.split()[self.index]
		path = parts.split('/')
		p = path[1].replace('PROJ', '')
		r = path[2].replace('RUN', '')
		c = path[3].replace('CLONE', '')
		g = path[4].split('.')[0].replace('frame', '')
		return (int(p), int(r), int(c), int(g))

CoreError = Error('Core error', type0, -1)
PushJobSingle = Error('PushJobSingle: XYZ job file exists', type0, -2)
TPRFileExists = Error('TPR File exists', type1, -2)
TRRFileExists = Error('TRR (traj) File exists', type1, -2)
RETRY_MAXExceeded = Error('RETRY_MAX exceeded', type0, -1)
text2type = {'Core error': CoreError,
 'PushJobSingle': PushJobSingle,
 'TPR File': TPRFileExists,
 'TRR File': TRRFileExists,
 'FAULTYWU': RETRY_MAXExceeded}
t2t_keys = text2type.keys()

class FAHErrorLog( FAHBaseType ):

	def __init__(self, errlogfile):
		self.errlogfile = abspath(errlogfile)
		self.wulist = {}
		self.errlist = {}
		self.wusbyproject = {}
		for key in t2t_keys:
			self.errlist[key] = []
		
		ERRLOG = open(self.errlogfile)
		errlog = ERRLOG.readlines()
		ERRLOG.close()
		for line in errlog:
			for key in t2t_keys:
				if key in line:
					errtype = text2type[key]
					prcg = errtype.getPRCG(line)
					job = FAHJob( prcg )
					self.wulist[job] = errtype.name
					self.errlist[key].append(job)
					pnum = job['proj']
					if pnum not in self.wusbyproject.keys(): 
						self.wusbyproject[pnum] = {} 
					try:
						self.wusbyproject[pnum][job.name]=(job, errtype.name)
					except KeyError:
						self.wusbyproject[pnum] = []
						self.wusbyproject[pnum][job.name]=(job, errtype.name)

#errlog = FAHErrorLog( "/home/server/server2/Error.log" )
