#!/usr/bin/env python
#
# Copyright (C) 2014 Narf Industries <info@narfindustries.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#

from generator.actions import Actions, Variable
from random import choice, randint
from os.path import dirname, abspath, join
import sys


sys.path.append(join(dirname(dirname(dirname(abspath(__file__)))), "support"))
import support as sp
from gofish import GoFish, Card



class FishyXml(Actions):

	DEBUG = False
	DEBUG_ERR = DEBUG or False
	DEBUG_FUNC = DEBUG or False
	DEBUG_INIT = DEBUG or False
	FAIL_CHANCE = 0.001

	def start(self):
		self.state['g'] = GoFish(sp.random_string(5, 20))

	def _recv_error(self, error_name):
		expected = sp.serialize_error(error_name)
		self.read(length=len(expected), expect=expected)
		if True == self.DEBUG_ERR:
			print('exiting due to {0}'.format(error_name))

	def _books(self):
		'''
		Process the act of removing books from hand and reporting the count.
		'''
		turn = self.state['g'].get_turn_pid()
		count = self.state['g'].books_qty()

		if True == self.DEBUG_FUNC:
			print "pid {0} books this turn: {1}".format(turn, count)

		msg = sp.serialize_books(count)

		if 0 == turn:
			self.write(msg)
		else:
			self.read(length=len(msg), expect=msg)

		return 0

	def _fishing(self, rank):
		'''
		Process the act of going fishing.
		'''
		turn = self.state['g'].get_turn_pid()
		if True == self.DEBUG_FUNC:
			print "pid {0} going fishing.".format(turn)

		FAIL = ''
		if 0 == turn:
			if self.chance(self.FAIL_CHANCE): # correct len, wrong tags for this msg
				msg = sp.serialize_draw_request()
				FAIL = 'ERR_INVALID_XML'
			else:
				msg = sp.serialize_fishing()