import time
import random
import datetime
import telepot


def parse_command(cmd):
	if len(cmd) != 2:
		return None
	if cmd[0].lower() not in ['x', 'o']:
		return None
	if not cmd[1].isdigit():
		return None
	if int(cmd[1]) == 0:
		return None
	return cmd[0].lower(), int(cmd[1])

def printable_grid():
	global tris
	return str('Grid:' + '\n' + ' '.join(tris[0:3]) + '\n' + ' '.join(tris[3:6]) + '\n' + ' '.join(tris[6:9]))

def play(sym, cell):
	global tris
	if tris[cell] == '-':
		tris[cell] = sym
		return True
	else:
		return False

def reset():
	global tris
	tris = list('-' * 9)

	

def handle(msg):
	chat_id = msg['chat']['id']
	command = msg['text']

	# print('Got command: ' + str(parse_command(command)))

	cmd = parse_command(command)
	if cmd is not None:
		if play(cmd[0], cmd[1]-1):
			bot.sendMessage(chat_id, printable_grid())
		else:
			bot.sendMessage(chat_id, 'Cell already taken!')
			bot.sendMessage(chat_id, printable_grid())
	elif command == '/schema':
		bot.sendMessage(chat_id, printable_grid())
	elif command == '/reset':
		reset()
		bot.sendMessage(chat_id, "Ready for a new game")
	else:
		bot.sendMessage(chat_id, "invalid command")

tris = []
reset()
bot = telepot.Bot('##########you-key-here#########')
bot.message_loop(handle)
print('I am listening ...')

while 1:
    time.sleep(10)



