import sys
import os
import csv
import jsonschema
import json
from datetime import time, datetime, timedelta

##player neighbors
## ------------------------------
def getLetters(numlines,jreader,rowname1,rowname2,rowid1,rowid2):
    """
    	jreader: json file
    """
    letters=[]
    letterslist=[]
    for i in range(numlines):
    	if jreader[i][rowname1]== rowid1 and jreader[i][rowname2]== rowid2:
    		letters=jreader[i]["beginparameters"]
    		
    		for index,row in enumerate(letters):
    			if letters[index]["parameter"]=="letter1":
    				letterslist.append(letters[index]["value"])
    			if letters[index]["parameter"]=="letter2":
    				letterslist.append(letters[index]["value"])
    			if letters[index]["parameter"]=="letter3":
    				letterslist.append(letters[index]["value"])
    return ",".join(str(x) for x in letterslist)

## ------------------------------
def getPhase(numlines,jreader,rowname1,rowid1):
    """
    	jreader: json file
    """
    begin=0
    numseconds=0
    n=0
    d=0
    experimentid=0
    for i in range(numlines):
    	if jreader[i][rowname1]== rowid1 :
    		begin=jreader[i]["begin"]
    		numseconds=jreader[i]["duration"]
    		n=jreader[i]["n"]
    		d=jreader[i]["d"]
    		experimentid=jreader[i]["experimentid"]

    return begin,numseconds,n,d,experimentid

## ------------------------------
def getPlayers(numlines,jreader,rowname1,rowid1):
    """
    	jreader: json file
    """
    players=[]
    playerslist=[]
    for i in range(numlines):
    	if jreader[i][rowname1]== rowid1 :
    		players=jreader[i]["activeplayers"]
    for index,row in enumerate(players):
    	playerslist.append(players[index]["player"])

    return playerslist
      
##player interaction json file for visualization

## ------------------------------
def getEvents(windowsize,allactions,numsecondsvalue):
	eventsplayer=[]
	#timer=windowsize
	timer=1
	requestsent=[]
	replyreceived=[]
	requestreceived=[]
	replysent=[]
	words=[]
	aftersecond=''
	lenactions = len(allactions)
	for index,row in enumerate(allactions):
		upsecond=int(row[1])
		if upsecond>=0 and upsecond<numsecondsvalue:
			for i in range(timer,upsecond):	
				if index<(lenactions-1):
					aftersecond=allactions[index+1][1]
				else:
					aftersecond=''
				if timer%windowsize==0 and aftersecond!=upsecond:
					requestsentstring="-".join(str(x) for x in requestsent)
					replyreceivedstring="-".join(str(x) for x in replyreceived)
					requestreceivedstring="-".join(str(x) for x in requestreceived)
					replysentstring="-".join(str(x) for x in replysent)
					wordstring="-".join(str(x) for x in words)
					eventsplayer.append([requestsentstring,replyreceivedstring,requestreceivedstring,replysentstring,wordstring])
					requestsent=[]
					replyreceived=[]
					requestreceived=[]
					replysent=[]
					words=[]
				if aftersecond!=upsecond:
					timer=timer+1
			if str(row[0])=='requestSent':
				requestsent.append(row[2])
			if str(row[0])=='replyReceived':
				replyreceived.append(row[2])
			if str(row[0])=='requestReceived':
				requestreceived.append(row[2])
			if str(row[0])=='replySent':
				replysent.append(row[2])
			if str(row[0])=='word':
				words.append(row[2])
			if timer%windowsize==0 and aftersecond!=upsecond:
				requestsentstring="-".join(str(x) for x in requestsent)
				replyreceivedstring="-".join(str(x) for x in replyreceived)
				requestreceivedstring="-".join(str(x) for x in requestreceived)
				replysentstring="-".join(str(x) for x in replysent)
				wordstring="-".join(str(x) for x in words)
				eventsplayer.append([requestsentstring,replyreceivedstring,requestreceivedstring,replysentstring,wordstring])
				requestsent=[]
				replyreceived=[]
				requestreceived=[]
				replysent=[]
				words=[]
			if aftersecond!=upsecond:
				timer=timer+1

	for i in range(timer,numsecondsvalue+1):
		if timer%windowsize==0:
			requestsentstring="-".join(str(x) for x in requestsent)
			replyreceivedstring="-".join(str(x) for x in replyreceived)
			requestreceivedstring="-".join(str(x) for x in requestreceived)
			replysentstring="-".join(str(x) for x in replysent)
			wordstring="-".join(str(x) for x in words)
			eventsplayer.append([requestsentstring,replyreceivedstring,requestreceivedstring,replysentstring,wordstring])	
			requestsent=[]
			replyreceived=[]
			requestreceived=[]
			replysent=[]
			words=[]		
		timer=timer+1

	return(eventsplayer)

## ------------------------------
def returnJson(numlines,jreader,rowname,phasesids,phasefile,experimentfile,cat1numletters,cat1time,cat2numwords,cat2time,nvalue,dvalue,numsecondsvalue,csvtimeline,csvtimelinecat1,csvtablecat):
    """
    	jreader: json file
    """
    data=[]
    alldatajson=[]
    jsonfilename = phasefile
    json_phase = open(jsonfilename, 'r')
    phase_data = json.load(json_phase)
    numlinesphase= len(phase_data)
    jsonfilename = experimentfile	
    json_experiment = open(jsonfilename, 'r')
    experiment_data = json.load(json_experiment)
    numlinesexperiment= len(experiment_data)
    
    for i in range(numlines):
    	if jreader[i][rowname]in phasesids:
    		actions=jreader[i]["actionlist"]
    		for index,row in enumerate(actions):
    			data.append([actions[index]["player1"],actions[index]["player2"],actions[index]["actionid"],actions[index]["playerActionSeqid"],actions[index]["timestamp"],actions[index]["payload"]])
    for phase in phasesids:  	
    	#print(phase)
    	json_phase.seek(0)
    	begin,numseconds,n,d,experimentid=getPhase(numlinesphase,phase_data,"phaseid",phase)
    	numseconds=int(numseconds)
    	numsecondsvalue=int(numsecondsvalue)
    	if str(nvalue)==str(n) and str(dvalue)==str(d):
    		#print("yes")
    		json_experiment.seek(0)
    		players=getPlayers(numlinesexperiment,experiment_data,"experimentid",experimentid)
    		#print(players)
    		countplayer=len(players)
    		playersactions=[]
    		for player in players:
    			#json_player.seek(0)
    			#letterstring=getLetters(numlinesplayer,player_data,"phaseid","playerid",phase,player)
    			#print(player)
    			#print(letterstring)
    			#allactions=[]
    			numrequestsent=0
    			numreplyreceived=0
    			cat1flag=0
    			cat2flag=0
    			cat2flag2=0
    			countletters=0
    			timesecondsflag=0
    			countwords=0
    			timesecondsflag2=0
    			timesecondsbegin=0
    			timesecondsbegin2=0
    			#print(data)
    			allwordsplayer=[]
    			category1=[]
    			category2=[]
    			csvtimeline.write(str(experimentid)+','+str(player)+',n'+str(n)+'d'+str(d)+',')
    			csvtimelinecat1.write(str(experimentid)+','+str(player)+',n'+str(n)+'d'+str(d)+',')
    			csvtablecat.write(str(experimentid)+','+str(player)+',n'+str(n)+'d'+str(d)+',')
    			for row in data:
    				if row[0]==player and row[2]=="word":
    					timeseconds=int(float(row[4])-float(begin))
    					allwordsplayer.append([row[5],timeseconds])
    			for row in data:
    				#if row[1]==player and row[2]=="requestsent":
    				#	allactions.append(['requestReceived',int(float(row[4])-float(begin)),row[5]])
    				#if row[0]==player and row[2]=="replysent":
    				#	allactions.append(['replySent',int(float(row[4])-float(begin)),row[5]])
    				if row[1]==player and row[2]=="replysent":
    					numreplyreceived=numreplyreceived+1
    					timeseconds=int(float(row[4])-float(begin))
    					timesecondsbegin=timeseconds+int(cat2time)
    					charletter=str(row[5]).lower()
    					countingwords=0
    					
    					for rowword in allwordsplayer:
    						#print(rowword)
    						if rowword[1]>timeseconds and rowword[1]<=timesecondsbegin:
    							if charletter in str(rowword[0]):
    								countingwords=countingwords+1
    								if countingwords==int(cat2numwords) and rowword[1]<numsecondsvalue:
    									category2.append(rowword[1])
    					if countingwords>=int(cat2numwords):
    						cat2flag2=cat2flag2+1
    					#allactions.append(['replyReceived',int(float(row[4])-float(begin)),row[5]])
    				if row[0]==player and row[2]=="requestsent":
    					numrequestsent=numrequestsent+1
    					timeseconds=int(float(row[4])-float(begin))
    					timesecondsbegin2=timeseconds+int(cat2time)
    					timesecondsflag2=0
    					if timesecondsflag==1:
    						if timeseconds<=timesecondsbegin:
    							countletters=countletters+1
    						if timeseconds>timesecondsbegin and countletters<int(cat1numletters):
    							timesecondsbegin=timeseconds+int(cat1time)
    							countletters=1
    					if timesecondsflag==0:
    						timesecondsflag=1
    						timesecondsbegin=timeseconds+int(cat1time)
    						countletters=countletters+1
    					if countletters==int(cat1numletters) and timeseconds<numsecondsvalue:
    						category1.append(timeseconds)
    						cat1flag=cat1flag+1
    						countletters=0
    						timesecondsflag=0
    					#allactions.append(['requestSent',int(float(row[4])-float(begin)),row[5]])
    				if row[0]==player and row[2]=="word":
    					timeseconds=int(float(row[4])-float(begin))
    					if timesecondsflag2==1:
    						if timeseconds<=timesecondsbegin2:
    							countwords=countwords+1
    						if timeseconds>timesecondsbegin2 and countwords<int(cat2numwords):
    							countwords=0
    							timesecondsflag2=2
    					if timesecondsflag2==0:
    						timesecondsflag2=1
    						if timeseconds<=timesecondsbegin2:
    							countwords=1
    					if countwords==int(cat2numwords):
    						cat2flag=cat2flag+1
    						countwords=0
    						timesecondsflag2=2
    					#allactions.append(['word',int(float(row[4])-float(begin)),row[5]])
    			if cat1flag>0 and cat2flag2>0:
    				playercategory=4
    			if cat1flag>0 and cat2flag2==0:
    				playercategory=1
    			if cat1flag==0 and cat2flag2>0:
    				playercategory=2
    			if cat1flag==0 and cat2flag2==0:
    				playercategory=3	
    			
    			category1.sort(key=int)
    			category2.sort(key=int)
    			stringcat="-".join(str(x) for x in category1)
    			csvtablecat.write(stringcat+',')
    			stringcat="-".join(str(x) for x in category2)
    			csvtablecat.write(stringcat+'\n')
    			
    			beginsecond=0
    			
    			print(category1)
    			indexcount=0
    			for index,row in enumerate(category1):
    				numtimes=category1.count(row)
    				
    				for x in range(beginsecond,row):
    					csvtimelinecat1.write('0,')
    				if indexcount==index:
    					csvtimelinecat1.write(str(numtimes))
    					if row==numsecondsvalue:
    						csvtimelinecat1.write('\n')
    					else:
    						csvtimelinecat1.write(',')
    					indexcount=indexcount+numtimes
    				beginsecond=row+1
    			
    			for x in range(beginsecond,numsecondsvalue):
    				if x==(numsecondsvalue-1):
    					csvtimelinecat1.write('0\n')
    				else:
    					csvtimelinecat1.write('0,')
    					
    			beginsecond=0
    			#print(category2)
    			indexcount=0
    			for index,row in enumerate(category2):
    				numtimes=category2.count(row)
    				for x in range(beginsecond,row):
    					csvtimeline.write('0,')
    				if indexcount==index:
    					csvtimeline.write(str(numtimes))
    					if row==numsecondsvalue:
    						csvtimeline.write('\n')
    					else:
    						csvtimeline.write(',')
    					indexcount=indexcount+numtimes
    				beginsecond=row+1
    				
    			for x in range(beginsecond,numsecondsvalue):
    				if x==(numsecondsvalue-1):
    					csvtimeline.write('0\n')
    				else:
    					csvtimeline.write('0,')
    				
    			#allactions=sorted(allactions,key=lambda x: x[1])
    			#print(allactions)
    			#eventssplayer=getEvents(windowsize,allactions,numsecondsvalue)
    			playersactions.append([player,playercategory,numrequestsent,numreplyreceived])
    			#alleventArray = sorted(alleventArray, key=lambda a_entry: a_entry[2])
    			
    		alldatajson.append([phase,playersactions])
    
    return alldatajson
    
### -----------------------------
### Start.
def main(experimentfile,phasedescfile,phasefile,actionfile,featureid,cat1numletters,cat1time,cat2numwords,cat2time,nd,numseconds):
		
    featurejson=open(os.getcwd()+'/data-analytics-pipeline/json-schema/h9/input/datasets/h9.json', 'w')
    featurejson2=open(os.getcwd()+'/property-inference-pipeline/json-schema/inputTransformation/datasets/h9.json', 'w')
    
    csvtimeline = open(os.getcwd()+'/data-analytics-pipeline/test/results/h9/output/all/timelineCat2Player.csv', 'w')
    csvtimeline.write('session,player,type,')
    
    csvtimelinecat1 = open(os.getcwd()+'/data-analytics-pipeline/test/results/h9/output/all/timelineCat1Player.csv', 'w')
    csvtimelinecat1.write('session,player,type,')
    
    csvtablecat = open(os.getcwd()+'/data-analytics-pipeline/test/results/h9/output/all/tableCatPlayer.csv', 'w')
    csvtablecat.write('session,player,type,cat1Times,cat2Times\n')
    
    for x in range(0,numseconds):
    	if x==numseconds-1:
    		csvtimeline.write(str(x)+'\n')
    		csvtimelinecat1.write(str(x)+'\n')
    	else:
    		csvtimeline.write(str(x)+',')
    		csvtimelinecat1.write(str(x)+',')
    					
    jsonfilename = phasedescfile
    json_phasedesc = open(jsonfilename, 'r')
    phasedesc_data = json.load(json_phasedesc)
    numlinesphasedesc= len(phasedesc_data)
    allfeatures=[]
    phases=[]
    phasesids=[]
    #print(phasedesc_data)
    for i in range(numlinesphasedesc):
    	features=phasedesc_data[i]["features"]
    	for index,row in enumerate(features):
    		if features[index]["feature"]!="":
    			allfeatures.append(features[index]["feature"])
    			if phasedesc_data[i]["phaseid"] not in phases:
    				phases.append(phasedesc_data[i]["phaseid"])
    
    jsonfilename = phasefile	
    json_phase = open(jsonfilename, 'r')
    phase_data = json.load(json_phase)
    numlinesphase= len(phase_data)		
    allfeaturesjsondata=[]
    for i in range(numlinesphase):
    	if phase_data[i]["phasedescriptionid"] in phases:
    		phasesids.append(phase_data[i]["phaseid"])

    ndlist=nd.split(",")
    for ndvalue in ndlist:
    	n,d=ndvalue.split("d")
    	v,n=n.split("n")
    	#print(n)
    	#print(d)
    	jsonfilename = actionfile	
    	json_action = open(jsonfilename, 'r')
    	action_data = json.load(json_action)
    	numlinesaction= len(action_data)
    	#phasesids=["5ydhsfg61"]
    	#print(phasesids)
    	featuresjson=returnJson(numlinesaction,action_data,"phaseid",phasesids,phasefile,experimentfile,cat1numletters,cat1time,cat2numwords,cat2time,n,d,numseconds,csvtimeline,csvtimelinecat1,csvtablecat)
    	allfeaturesjsondata.append([n,d,cat1numletters,cat1time,cat2numwords,cat2time,numseconds,featuresjson])
    		
    	#interactionjsondata=[{"phaseid":str(row[0]),"begin":str(row[1]),"n":int(row[2]),"d":int(row[3]),"duration":int(row[4]),"players":[{"timestamp":str(row2[0]),"second":int(row2[1]),"playeridint":int(row2[2]),"payload":str(row2[3]),"playerid":str(row2[4]),"initialparameter":str(row2[5]),"actionid":str(row2[6])} for row2 in row[5]]} for row in alldatajson] 
    #print(allfeaturesjsondata)
    featuresjsondata=[{"features":[{"n":int(row[0]),"d":int(row[1]),"cat1numletters":int(row[2]),"cat1time":int(row[3]),"cat2numwords":int(row[4]),"cat2time":int(row[5]),"numseconds":int(row[6]),"phases":[{"phaseid":str(row2[0]),"players":[{"playerid":str(row3[0]),"category":int(row3[1]),"requestsent":int(row3[2]),"repliesreceived":int(row3[3])}for row3 in row2[1]]}for row2 in row[7]]}]} for row in allfeaturesjsondata]
    json.dump(featuresjsondata,featurejson,indent=2)
    json.dump(featuresjsondata,featurejson2,indent=2)
    print (" -- h9 Transformation --")
    print (" -- good termination --")

## --------------------------
## Execution starts.
if __name__ == '__main__':
		
    if (len(sys.argv) != 9):
    	print ("  Error.  Incorrect usage.")
    	print ("  usage: exec infile outfile.")
    	print ("  Halt.")
    	quit()
    	
    experimentfile=sys.argv[1]
    phasedescfile=sys.argv[2]
    phasefile=sys.argv[3]
    actionfile=sys.argv[4]
    featureid=sys.argv[5]
    windowsize=sys.argv[6]
    nd=sys.argv[7]
    numseconds=sys.argv[8]
    main(experimentfile,phasedescfile,phasefile,actionfile,featureid,windowsize,nd,numseconds)
    
    