from getchar import *
from Interface import Interface
class TextInterface(Interface):
    def __init__(self,game):
	self.m_game = game
    
    def playLoop(self):
	while(True):
	    while(self.playing()):
		self.show()
		print "select a move:"
		print "n)ew game"
		print "u)ncover"
		print "f)lag"
		print "c)heck"
		print "q)uit"
		input = raw_input()
		while (not self.parseInput(input)):
		    self.show()
		    print "select a move:"
		    print "n)ew game"
		    print "u)ncover"
		    print "f)lag"
		    print "c)heck"
		    print "q)uit"
		    input = raw_input()
	    self.setPlaying(True)
	    self.setupGame()

    def startNewGame(self):
	self.setupGame()
	self.playLoop()

    def setupGame(self):
	match = False
	input = ""
	c = ' '
	while ((c != 'n' and c !='q')):
	    print "n)ew game"
	    print "q)uit"

	    c = getchar()
	if c == 'q':
	    self.m_game.quit()
	else: # c == 'n'
	    while(not match):
		print "Please select game type:"
		print "b)eginner: 8x8"
		print "i)ntermediate: 16x16"
		print "e)xpert: 30x16"
		print "q)uit"
		c = getchar()
		match = True
		if c == 'b':
		    self.m_game.initField(8,8,6)
		elif c == 'i':
		    self.m_game.initField(16,16,25)
		elif c == 'e':
		    self.m_game.initField(30,16,48)
		elif c == 'q':
		    print "Okay."
		    self.m_game.quit()
		else:
		    match = False
		    print "Invalid input."
	self.setPlaying(True)

    def uncover(self, x, y):
	res = self.m_game.getField().uncover(x,y)
	if res == -1:
	    print "That was a mine!"
	    self.lose()
	elif self.m_game.getField().remaining() == 0:
	    self.win()

    def check(self, x, y):
	res = self.m_game.getField().check(x,y)
	if result:
	    print "Oops, one of your flags was wrong."
	    self.lose()
	elif m_game.getField().remaining() == 0:
	    self.win()

    def show(self):
	self.m_game.getField().outputAsString()
    
    def parseInput(self, input):
	args = input.split()
	if len(args) < 1:
	    print "You need to provide input"
	    return False
	comm = args[0]
	if comm == 'q':
	    self.m_game.quit()
	elif comm != 'n':
	    if len(args) != 3:
		print "Not enough arguments!"
		return False
	    arg1 = int(args[1])
	    arg2 = int(args[2])
	if comm == 'u':
	    self.uncover(arg1, arg2)
	elif comm == 'c':
	    self.check(arg1,arg2)
	elif comm == 'f':
	    self.flag(arg1,arg2)
	else:
	    print "unknown command"
	    return False
	return True

    def flag(self, x, y):
	self.m_game.getField().flag(x,y)

    def win(self):
	print "Congratulations!  You have emerged triumphant!"
	self.setPlaying(False)

    def lose(self):
	print "You have suffered an ingnominious defeat!"
	self.setPlaying(False)

    def quit(self):
	print "Goodbye!"
	self.m_game.quit()
	
    def setGame(self, game):
	self.m_game = game

    def setPlaying(self, p):
	self.m_playing = p
    
    def playing(self):
	return self.m_playing
