"""
This file is part of the Tetris project.

Written 2023 by Maarten Tromp <maarten@geekabit.nl>


Website
-------
https://www.geekabit.nl/projects/tetris-window/


License
-------
CC0 (no copyright, public domain)
The person who associated a work with this deed has dedicated the work to the public domain by
waiving all of his or her rights to the work worldwide under copyright law, including all related
and neighbouring rights, to the extent allowed by law. You can copy, modify, distribute and perform
the work, even for commercial purposes, all without asking permission.
https://creativecommons.org/share-your-work/public-domain/cc0/
"""


class Replayer:
	"""
	Replayer class. Plays back a recorded game.
	"""


	def __init__(self, replay_data):
		"""
		An instance of this class is created when a new player connects to the controller websocket.

		Parameters
		----------
		replay_data: list
			List of rle-encoded button states.
		"""

		# public variables
		self.id = -1 # I have no ID
		self.name = "REPLAYER"
		self.game = "replay"
		self.state = "replay"
		self.replay = replay_data

		# private variables
		self._button_state = {"up" : 0, "down" : 0, "left" : 0, "right" : 0, "b" : 0, "a" : 0}
		self._rle_count = 0
		self._rle_counter = 0
		self._replay_style = "old"

		# init
		if isinstance(self.replay[0], int):
			# new style
			self._rle_count = self.replay.pop(0)
			self._replay_style = "new"


	def send(self, _):
		"""
		Empty function to mimic Player behaviour.

		Parameters
		----------
		message: string
			Not used.

		Returns
		-------
		bool
			none
		"""

		return


	def get_button_state(self):
		"""
		Return replay data for button state.

		Parameters
		----------
		none

		Returns
		-------
		dict
			Copy of internal dict with all buttons and number of frames the button has been pressed.
		"""

		if self._replay_style == "old":
			if len(self.replay) >= 1:
				return self.replay.pop(0)
			return {"up" : 0, "down" : 0, "left" : 0, "right" : 0, "b" : 0, "a" : 0}

		# new style
		if self._rle_counter < self._rle_count:
			self._rle_counter += 1
			return self._button_state
		if len(self.replay) < 1:
			return self._button_state
		self._button_state = self.replay.pop(0)
		if len(self.replay) < 1:
			return self._button_state
		self._rle_count = self.replay.pop(0)
		self._rle_counter = 0
		return self._button_state

		#if self._rle_counter >= self._rle_count:
		#	if len(self.replay) >= 1:
		#		self._button_state = self.replay.pop(0)
		#		if len(self.replay) >= 1:
		#			self._rle_count = self.replay.pop(0)
		#			self._rle_counter = 0
		#else:
		#	self._rle_counter += 1
		#return self._button_state
