#!/usr/bin/env python

# Copyright 2003 Tom Rothamel <tom-potw@rothamel.us>
# 
# 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.

import curses
import optparse
import time

digits = {
    ':' : ( ':', ':', ':', ':' ),
    ' ' : ( ' ', ' ', ' ', ' ' ),
    
    '0' : ( '.', '.', '.', '.' ),
    '1' : ( '.', '.', '.', 'O' ),
    '2' : ( '.', '.', 'O', '.' ),
    '3' : ( '.', '.', 'O', 'O' ),
    '4' : ( '.', 'O', '.', '.' ),
    '5' : ( '.', 'O', '.', 'O' ),
    '6' : ( '.', 'O', 'O', '.' ),
    '7' : ( '.', 'O', 'O', 'O' ),
    '8' : ( 'O', '.', '.', '.' ),
    '9' : ( 'O', '.', '.', 'O' ),
    }

def bcdtime():
    """
    This returns four strings, which together comprise the BCD
    representation of the current time. The first string contains the
    most significant bits of the numbers, with the fourth containing
    the least significant bits.
    """

    st = time.strftime("%02H : %02M : %02S")

    rv = []

    # For each bit-place, from MSB to LSB
    for i in range(0, 4):
        rs = ""

        # For each place in the current time.
        for c in st:
            rs += digits[c][i]

        rv.append(rs)

    return rv


def curses_clock():
    """
    This displays a binary-coded-decimal clock in a terminal, using
    curses. The display updates every second.
    """

    scr = curses.initscr()

    # We put everything to do with curses in a try block, so that if
    # an error occurs, we call endwin() before displaying the
    # traceback.
    
    try:    
        # We only wait for input for a maximum of 1 second, or 10/10
        # seconds as specified here.
        curses.halfdelay(10)
        curses.noecho()

        while True:

            # Show the BCDtime.
            lines = bcdtime()

            for i, l in enumerate(lines):
                scr.addstr(i, 0, l)

            # Move the cursor out of the way.
            maxy, maxx = scr.getmaxyx()
            scr.move(maxy - 1, maxx - 1)            
            scr.refresh()

            # If we get 'Q', quit. This can take up to 1 second.
            c = scr.getch()
            if c == ord('q') or c == ord('Q'):
                break

    finally:
        curses.endwin()


def main():
    op = optparse.OptionParser(usage="bcd.py [options]",
                               version="bcd.py 1")

    op.add_option("--single", action="store_true", dest="single",
                  default=False,
                  help="Print out the current time, then quit.")

    options, args = op.parse_args()

    # If single, print out the current bcdtime, and exit.
    if options.single:
        for l in bcdtime():
            print l

        return

    curses_clock()

if __name__ == "__main__":
    main()

        
    
