#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# gameclock - a simple chess/game clock
# Copyright (C) 2008 Antoine Beaupré <anarcat@koumbit.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import time
import math
import getopt
import sys

version = "2.1"
verbose = 0 # 0 means not verbose, higher numbers show more information, see maybe_print for more info

class Clock:
    """The main clock engine

    Each clock is an instance of this class. This could be considered
    like a merge between a controler and a model in an MVC
    model. However, this software isn't based on the MVC model in any
    remote way.
    
    This should be pretty precise and doesn't lag from empirical
    observations (watching the clocks compared to the Gnome clock
    applet)
    """
    last_start = 0 # 0 if stopped
    text = "" # rendered version of the clock
    dead = False
    game = None
    # a clock is part of a chained list
    next = None
    # usually, clocks go backwards, but some games might require it to go other ways
    factor = -1

    def __init__(self, game, delay = None):
        """Setup the clock engine
        
        The clock is stopped by default and the display is refreshed
        """
        self.time = game.default_time
        self.dead = self.time < 0 # calculated only after update() and should be used only this way, it is a cache
        self.game = game
        self.update()

    def start(self):
        """Start the timer
        
        This marks the new timestamp and sets the background color
        """
        self.last_start = time.time()
        # no need to update, time shouldn't have changed since last stop

    def stop(self):
        """Stop the timer
        
        This computes the new cumulatative time based on the start
        timestamp. It resets the timestamp to zero to mark the timer as
        stopped.
        
        This also resets the event box's color and triggers an update of
        the label.
        
        XXX: Note that this function takes *some* time to process. This
        time is lost and not given to any participant. Maybe that should
        be fixed for the clock to be really precised, by compensation
        for the duration of the function.
        
        Another solution would be to create a thread for the Game engine
        """
        if self.last_start:
            self.time = self.get_time()
            self.last_start = 0
        self.update()

    def pause(self):
        """pause/unpause the timer
        
        this will start the timeer if stopped and stop it if started
        """
        if self.last_start:
            self.time = self.get_time()
            self.last_start = 0          
            self.update()
        else:
            self.start()

    def running(self):
        return self.last_start

    def get_time(self):
        """return the current time of the clock in ms"""
        if self.last_start:
            diff = time.time() - self.last_start
        else:
            diff = 0
        return self.time + (self.factor * diff*1000)

    def update(self):
        """Refresh the display of the clock's widget"""
        # convert to seconds because that's what gmtime wants
        miliseconds = self.get_time()
        secs = miliseconds/1000
        self.text = time.strftime("%H:%M:%S", time.gmtime(abs(secs)))
        days = abs(secs) / ( 24 * 60 * 60 )
        if days >= 1:
            self.text = "%dd " % days + self.text
        self.dead = secs < 0
        if self.dead:
            self.text = "-" + self.text
        if self.game.miliseconds:
            mantissa = abs(miliseconds) - (math.floor(abs(secs))*1000)
            self.text += ".%03d" % (mantissa)
        return self.text

    def __str__(self):
        """make a better string representation of the objects
        
        we basically dump all variables and some functions
        """
        return "  clock engine %s time: %d last: %d diff: %f dead: %d text: %s\n  next %s" % ( object.__str__(self), self.time, self.last_start, time.time() - self.last_start, self.dead, self.text, self.next)

class ChessClock(Clock):
    """A typical Chess clock
    
This clock will stop at the end of your turn, and should represent fairly faithfully tabletop chess clocks.

A typical setting is 5 minutes each, which is considered to be a "blitz". 2 minutes is often called "lightning chess".
    """
    # this is just an alias to the base Game class which implements everything
    pass


class FisherClock(Clock):
    """A chess clock, as modified by Garry Fisher

This is a regular chess clock with one little twist: every time a player finishes its turn, he gets extra time. This allows for timed game that are still fairly interactive, as the player is forced to move within a certain timeframe.

A typical setting is 2 minutes + 10 seconds delay, which leads to games of around 10 to 20 minutes."""
    delay = 10

    def __init__(self, game, delay):
        Clock.__init__(self, game, delay)
        self.delay = delay
    
    def stop(self):
        """end the turn, fisher style

        this increments the current clock before switching turns as normal
        """
        self.time += self.delay
        Clock.stop(self)

class BoardClock(Clock):
    """A simple clock for general board games.

A player gets a specific amount of time to play his turn, but the leftover time isn't carried over to the next turn."""

    # we need to remember the original time
    default_time = None

    def __init__(self, game, delay = None):
        Clock.__init__(self, game, delay)
        self.default_time = self.time

    def stop(self):
        """override the end_turn function to reset the timers at the end of turns"""
        Clock.stop(self)
        self.time = self.default_time
        self.update()

class HourglassClock(Clock):
    """Hourglass emulation.

This clock is similar to having an hourglass on a table that is flipped at the end of each turn.

We do allow each player to start with a certain amonut of time (or "sand", if you will) on his side, in other words, this is as if the hourglass was half-empty/half-full when the game starts.

Note that this doesn't make much sense with more than two players..."""

    def __init__(self, game, delay = None):
        """this overrides the base constructor to make only one clock have an initial time

        basically, this is to represent that when you start it, the hour glass is empty on one side
        """
        Clock.__init__(self, game, delay)

    def start(self):
        """reimplement the start() function altogether

        make sure all the clocks are started and they are in the right direction
        """
        Clock.stop(self)
        self.factor = -1
        Clock.start(self)

    def stop(self):
        """reimplement the end_turn function altogether

        we go to the next clock, stop it, reverse its direction and
        start it again
        """
        Clock.stop(self)
        self.factor = 1
        Clock.start(self)


class Game:
    """the game engine
    
    this regroups two clocks and handles turn switches

    to simplify the code logic, this is basically the "Blitz" mode
    """

    # the number of turns played
    turns = 0
    miliseconds = False
    mode = 'blitz'
    
    default_time = 2 * 60 * 1000 # in ms
    default_players = 2 # default number of players
    clock_type = ChessClock # the default game type. note that this cannot be FisherGame because of the way the UI is setup.

    # the clocks in the game
    #
    # in chess there are two clocks, but there can be more. this is simply a list
    cur_clock = None
    first_clock = None

    def __init__(self, clock_type, clocks, default_time, miliseconds, delay = None):
        self.miliseconds = miliseconds
        self.clock_type = clock_type
        self.default_time = default_time

        # the clock engines
        self.cur_clock = self.first_clock = p = self.clock_type(self, delay)
        for i in range(clocks-1):
            p.next = self.clock_type(self, delay)
            p = p.next

    def start(self):
        """start the game
        
        this basically starts the clock
        """
        self.cur_clock.start()
        self.cur_clock.update()

    def end_turn(self):
        """end the turn
        
        this is the handler for the main button. it will stop the
        active clock and start the other and switch the active clock
        """
        self.cur_clock.stop()
        # XXX: we might lose a few ms here
        self.cur_clock = self.next_clock()
        self.cur_clock.start()
        self.turns += 1

    def next_clock(self):
        return self.cur_clock.next or self.first_clock

    def pause(self):
        """pause the game
        
        this just pauses the current clock
        """
        self.cur_clock.pause()

    def switch_clock(self):
        """change the current clock"""
        self.cur_clock = self.next_clock()

    def get_turns(self):
        """the number of complete turns played
        
        a 'complete turn' is a turn played by each player

        this is 1-based, i.e. when the game starts, it's turn 1, after
        every player has played once, it's turn 2, etc.
        """
        return math.floor(self.turns/self.count_players()) + 1

    def count_players(self):
        p = self.first_clock
        count = 0
        while p:
            count += 1
            p = p.next
        return count

    def dead(self):
        p = self.first_clock
        while p:
            if p.dead:
                return True
            p = p.next
        return False

    def running(self):
        return self.cur_clock.running()

    def __str__(self):
        """make a better string representation of the objects
        
        we basically dump all variables and some functions
        """
        return "  game engine %s\n  turns: %f / %d miliseconds: %d\n  first %s\n  current %s" % ( object.__str__(self), self.turns, self.get_turns(), self.miliseconds, self.first_clock, self.cur_clock)

def usage():
    """gameclock v%s  Copyright (C) 2008  Antoine Beaupré
This program comes with ABSOLUTELY NO WARRANTY.
This is free software, and you are welcome to redistribute it
under certain conditions.
For details see the COPYRIGHT file distributed along this program.

Usage:
  %s [ -h | -v ... | -f ]

  -h --help: display this help
  -v --verbose: display progress information to stdout. repeating the flag will show more information
  -f --fullscreen: start in fullscreen mode

See the manpage for more information."""
    print usage.__doc__ % (version, sys.argv[0])

if __name__ == "__main__":
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hvf:p:", ["help", "verbose", "fullscreen"])
    except getopt.GetoptError, err:
        # print help information and exit:
        usage()
        print "\nError: " + str(err) # will print something like "option -a not recognized"
        sys.exit(2)

    from gtkui import GameclockUI
    clock = GameclockUI()
    for o, a in opts:
        if o in ("-v", "--verbose"):
            clock.verbose += 1
        elif o in ("-h", "--help"):
            usage()
            sys.exit()
        elif o in ("-f", "--fullscreen"):
            clock.fullscreen = True
        else:
            assert False, "unhandled option"
    clock.maybe_print('running with verbosity: %d' % clock.verbose)
    clock.main()
