import os
import subprocess
import atexit
from threading import Timer
import string
import random

looptestPath = '/home/nonroot/.steam/steam/steamapps/common/Counter-Strike Source/cstrike/cfg/looptest.cfg'
consolelogPath = '/home/nonroot/.steam/steam/steamapps/common/Counter-Strike Source/cstrike/console.log'
iterationCap = 150

def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
	return ''.join(random.choice(chars) for _ in range(size))

def clearconsolelog():
	open(consolelogPath, 'w').close()

def writeCfgInput(Input):
	with open(looptestPath, 'w') as f:
		f.write(Input)

def getconsoleOutputForStatus(input):
	randomlygeneratedString = id_generator(11)
	str = "status; wait 5; {0}; wait 5; exec looptest.cfg;".format(randomlygeneratedString)
	print('writeCfgInput')
	writeCfgInput(str)
	checkConsoleOutput(randomlygeneratedString)
	incrementer = 0
	with open(consolelogPath, 'r') as f:
		for line in f:
			incrementer += 1
			if incrementer > iterationCap: return True #cap before leaving the file again
			if input in line: return False	#found hostname which means connected
	return True

def getConsoleOutputForTeams():
	teamvalues = ['Spectactor', 'Terrorist', 'Counter-Terrorist']
	randomlygeneratedString = id_generator(11)
	str = "sm_teaminfo; wait 50; {0}; wait 5; exec looptest.cfg;".format(randomlygeneratedString)
	while True:
		writeCfgInput(str)
		#is sm_team a command to show team?
		#maybe instead say !teaminfo, add sourcemod command to autism_bot_info.sp to print team to chat instead
		previousStr = ""
		checkConsoleOutput(randomlygeneratedString)
		with open(consolelogPath, 'r') as f:
			for line in f:
				print('getConsoleOutputForTeams line: ', line)
				if randomlygeneratedString in line:
					if teamvalues[2] in previousStr: return teamvalues[2]
					elif teamvalues[1] in previousStr: return teamvalues[1]
					return teamvalues[0]
				previousStr = line
                    
                    

def checkConsoleOutput(input):
	bool = False
	#print('entered checkconsole output')
	while not bool:
		with open(consolelogPath, 'r') as f:
			for line in f:
				if input in line:
					#print('line: ', line, ' \ninput: ', input)
					bool = True
					break

def resetCfgInputShortWait():
	#getpos
	randomlygeneratedString = id_generator(11)
	print('randomlygeneratedString: ', randomlygeneratedString)
	str = "wait 50; {0}; wait 50; exec looptest.cfg;".format(randomlygeneratedString)
	with open(looptestPath, 'w') as f:
		f.write(str)
	checkConsoleOutput(randomlygeneratedString)

def exit_handler():
	print('exithandler')
	#resetCfgInputShortWait()


def joinTeam():
	clearconsolelog()
	randomlygeneratedString = id_generator(11)
	str = "jointeam 2; wait 2; zspawn; wait 1; {0}; wait 5; exec looptest.cfg;".format(randomlygeneratedString)
	writeCfgInput(str)
	checkConsoleOutput(randomlygeneratedString)

def checkbotteam():
	print('reached checkbotteam')
	clearconsolelog()
	team = getConsoleOutputForTeams()
	print('team value: ', team)
	if "Spectactor" in team:
		joinTeam()

def checkIfConnected():
	clearconsolelog()
	randomlygeneratedString = id_generator(11)
	str1 = "connect 151.80.230.149:27015; wait 5; {0}; wait 500; exec looptest.cfg;".format(randomlygeneratedString)
	if (getconsoleOutputForStatus("hostname:")):
		writeCfgInput(str1)
		checkConsoleOutput(randomlygeneratedString)
		resetCfgInputShortWait()
	checkbotteam()
	resetCfgInputShortWait()
	followPlayer()

def followPlayer():
	randomlygeneratedString = id_generator(11)
	#setang 0 180 0;
	default_input = "+attack; wait 50; cl_minmodels; wait 50; +right; wait 50; +jump; wait 50; -jump; wait 50; +forward; wait 50; {0}; wait 5; exec looptest.cfg;".format(randomlygeneratedString)
	writeCfgInput(default_input)
	checkConsoleOutput(randomlygeneratedString)
	#print('start of method \n')


if __name__ == '__main__':
	atexit.register(exit_handler)
	clearconsolelog()
	resetCfgInputShortWait()
	checkIfConnected()