from threading import Timer
import time

class PlayerState:
    def __init__(self, display, specialDisplay, id, ballsToPlay, upperPlayfieldTime = 5, bonusTime = 0):
        self.display = display
        self.specialDisplay = specialDisplay
        self.__id = id
        self.__points = 0
        self.ballsLeft = ballsToPlay
        self.upperPlayfieldTime = upperPlayfieldTime
        self.bonusTime = bonusTime
        self.timer = None
        self.timerStartTime = None

    def addPoints(self, points):
        self.__points += points
        self.display.write_score(self.__points)

    def addBall(self):
        self.ballsLeft += 1
        self.specialDisplay.write_ballsToPlay(self.ballsLeft)

    def removeBall(self):
        self.ballsLeft -= 1
        self.specialDisplay.write_ballsToPlay(self.ballsLeft)
        if(self.ballsLeft == 0):
            # todo emit endgame Event
            pass

    def addUpperPlayfieldTime(self, time):
        self.upperPlayfieldTime += time

    def __setUpperPlayfieldTime(self, time):
        self.upperPlayfieldTime = time

    def startUpperPlayfieldTimer(self):
        self.timerStartTime = time.time()
        self.timer = Timer(self.upperPlayfieldTime, self.stopUpperPlayfieldTimer)

    def stopUpperPlayfieldTimer(self):
        if(self.timer == None):
            return

        self.timer.cancel()

        elapsedTime = time.time() - self.timerStartTime
        timeLeft = self.upperPlayfieldTime - elapsedTime
        self.__setUpperPlayfieldTime(timeLeft)

    def addBonusTimeSecond(self):
        self.bonusTime += 1

